【问题标题】:Uncaught ReferenceError: Popper is not defined - with Bootstrap 4 and Webpack 3.8.1未捕获的 ReferenceError:未定义 Popper - 使用 Bootstrap 4 和 Webpack 3.8.1
【发布时间】:2018-04-23 03:24:45
【问题描述】:

我正在使用带有 .NET Core 2.0 的 Visual Studio 2017 Angular 模板。该模板有许多我更新的旧依赖项,包括 Angular 5.0.0。使用 Bootstrap 3.x.x 运行 vanilla 模板可以工作。但是,使用 Bootstrap 4.0.0-beta.2 会导致以下错误:

Uncaught ReferenceError: Popper is not defined

我已尽我所能遵循此处的说明:

http://getbootstrap.com/docs/4.0/getting-started/webpack/

我看过这个问题:

Bootstrap 4: Uncaught ReferenceError: Popper is not defined

根据那里列出的解决方案,我必须在引导之前注册 popper,或者使用最小版本的 boostrap,因为它已经带有 popper。但是,我正在使用 webpack 2.5.1(我刚刚学习),我不知道如何在作为一部分提供的 webpack.config.js 文件中实现这两种解决方案模板,并包含 boostrap-webpack 文档所调用的修改。

webpack.config.js

const path = require('path');
const webpack = require('webpack');
const merge = require('webpack-merge');
const AotPlugin = require('@ngtools/webpack').AotPlugin;
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;

module.exports = (env) => {
    // Configuration in common to both client-side and server-side bundles
    const isDevBuild = !(env && env.prod);
    const sharedConfig = {
        stats: { modules: false },
        context: __dirname,
        resolve: { extensions: ['.js', '.ts'] },
        output: {
            filename: '[name].js',
            publicPath: 'dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
        },
        module: {
            rules: [
                { test: /\.ts$/, include: /ClientApp/, use: isDevBuild ? ['awesome-typescript-loader?silent=true', 'angular2-template-loader'] : '@ngtools/webpack' },
                { test: /\.html$/, use: 'html-loader?minimize=false' },
                { test: /\.css$/, use: ['to-string-loader', isDevBuild ? 'css-loader' : 'css-loader?minimize'] },
                { test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000' }
            ]
        },
        plugins: [new CheckerPlugin()]
    };

    // Configuration for client-side bundle suitable for running in browsers
    const clientBundleOutputDir = './wwwroot/dist';
    const clientBundleConfig = merge(sharedConfig, {
        entry: { 'main-client': './ClientApp/boot.browser.ts' },
        output: { path: path.join(__dirname, clientBundleOutputDir) },
        plugins: [
            new webpack.DllReferencePlugin({
                context: __dirname,
                manifest: require('./wwwroot/dist/vendor-manifest.json')
            }),
            new webpack.ProvidePlugin({
                $: 'jquery',
                jQuery: 'jquery',
                'window.jQuery': 'jquery',
                Popper: ['popper.js', 'default'],
                // In case you imported plugins individually, you must also require them here:
                //Util: "exports-loader?Util!bootstrap/js/dist/util",
                //Dropdown: "exports-loader?Dropdown!bootstrap/js/dist/dropdown"
            })
        ].concat(isDevBuild ? [
            // Plugins that apply in development builds only
            new webpack.SourceMapDevToolPlugin({
                filename: '[file].map', // Remove this line if you prefer inline source maps
                moduleFilenameTemplate: path.relative(clientBundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
            })
        ] : [
                // Plugins that apply in production builds only
                new webpack.optimize.UglifyJsPlugin(),
                new AotPlugin({
                    tsConfigPath: './tsconfig.json',
                    entryModule: path.join(__dirname, 'ClientApp/app/app.module.browser#AppModule'),
                    exclude: ['./**/*.server.ts']
                })
            ])
    });

    // Configuration for server-side (prerendering) bundle suitable for running in Node
    const serverBundleConfig = merge(sharedConfig, {
        resolve: { mainFields: ['main'] },
        entry: { 'main-server': './ClientApp/boot.server.ts' },
        plugins: [
            new webpack.DllReferencePlugin({
                context: __dirname,
                manifest: require('./ClientApp/dist/vendor-manifest.json'),
                sourceType: 'commonjs2',
                name: './vendor'
            })
        ].concat(isDevBuild ? [] : [
            // Plugins that apply in production builds only
            new AotPlugin({
                tsConfigPath: './tsconfig.json',
                entryModule: path.join(__dirname, 'ClientApp/app/app.module.server#AppModule'),
                exclude: ['./**/*.browser.ts']
            })
        ]),
        output: {
            libraryTarget: 'commonjs',
            path: path.join(__dirname, './ClientApp/dist')
        },
        target: 'node',
        devtool: 'inline-source-map'
    });

    return [clientBundleConfig, serverBundleConfig];
};

此外,这里是作为模板一部分提供的主入口点文件 boot.browser.ts

import 'reflect-metadata';
import 'zone.js';
import 'bootstrap';
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module.browser';

if (module.hot) {
    module.hot.accept();
    module.hot.dispose(() => {
        // Before restarting the app, we create a new root element and dispose the old one
        const oldRootElem = document.querySelector('app');
        const newRootElem = document.createElement('app');
        oldRootElem!.parentNode!.insertBefore(newRootElem, oldRootElem);
        modulePromise.then(appModule => appModule.destroy());
    });
} else {
    enableProdMode();
}

// Note: @ng-tools/webpack looks for the following expression when performing production
// builds. Don't change how this line looks, otherwise you may break tree-shaking.
const modulePromise = platformBrowserDynamic().bootstrapModule(AppModule);

【问题讨论】:

    标签: twitter-bootstrap angular webpack visual-studio-2017 asp.net-core-2.0


    【解决方案1】:

    尝试在引导之前而不是之后包含 Popper.js

     "../node_modules/popper.js/dist/umd/popper.min.js",
     "../node_modules/bootstrap/dist/js/bootstrap.min.js"
    

    【讨论】:

    • 是的,但是考虑到 webpack.config.js 基本上只是爬取 js 文件并捆绑它们,我该怎么做呢?鉴于特定库甚至没有列出,我如何告诉 webpack 包含顺序?我已经开始研究 webpack(我对它完全陌生),但还没有找到答案。
    • 你在哪里包括 bootstrap.js,你在使用 angular cli 吗?
    • 尝试使用 umd 发行版 'Popper': 'popper.js/dist/umd/popper' 而不是 Popper: ['popper.js', 'default'],
    • @Fateh Mohamed - 据我了解,bootstrap 包含在入口点文件 boot.browser.ts 中,popper 由 popper 行中的 webpack.config.js 处理:['popper .js','默认']。但就像我说的,我对 webpack 不熟悉,所以我不知道如何强制它先让 popper 进入或使用 umd 版本。我尝试按照您的建议替换 webpack 配置中的 popper: 行 Popper: 'popper.js/dist/umd/popper' 但这没有帮助
    • 不,我没有直接使用 Angular cli。我什至还没有创建任何组件。我只是在使用 vanilla 模板文件并尝试将其升级到 bootstrap 4(同时仍在使用 webpack)
    【解决方案2】:

    我安装了一个特定版本的 popper.js,我知道它正在使用 bootstrap 4.0.0-beta,如下所示:

    npm install popper.js@1.12.5 --save-dev
    

    然后我只需要像这样将它添加到我的 webpack.config.vendor.js 中:

    new webpack.ProvidePlugin(
                { 
                    $: 'jquery', 
                    jQuery: 'jquery', // }, Maps these identifiers to the jQuery package (because Bootstrap expects it to be a global variable)
                    jquery: 'jquery',
                    'window.jQuery': 'jquery',
                    Popper: 'popper.js/dist/umd/popper.js'                     
                }                
            ), 
    

    我不再收到 Uncaught ReferenceError: Popper is not defined 错误。

    我没有更改代码,只更改了 webpack 和 npm。

    【讨论】:

      【解决方案3】:

      我终于找到了克服错误的方法。我在主入口点 boot.browser.ts 文件中使用了以下几行:

      import * as $ from 'jquery';
      
      //These two lines didn't remove the error
      //import Popper from 'popper.js';
      //import 'bootstrap';
      
      //This one did remove the error. The bundle version of bootstrap includes popper in the correct order (according to the docs)
      import 'bootstrap/dist/js/bootstrap.bundle.js';
      

      有趣的是,引导 github (https://github.com/twbs/bootstrap/issues/24648) 上的建议代码是使用此行进行 jquery 导入:

      import $ from 'jquery'
      

      而不是

      import * as $ from 'jquery'
      

      但是前者导致了这个错误:

      找不到模块“jquery”的声明文件

      但是,我不知道这两行之间有什么区别

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-04-07
        • 2018-05-03
        • 2019-03-29
        • 2023-03-31
        • 2023-04-04
        • 2018-04-02
        • 1970-01-01
        相关资源
        最近更新 更多