【问题标题】:What is the best way to load Bootstrap with an ES6 import?使用 ES6 导入加载 Bootstrap 的最佳方法是什么?
【发布时间】:2016-09-23 22:34:06
【问题描述】:

我最近从使用 Require.js 切换到使用带有 Babel 的 WebPack。过去我会在我的 JS 模块中使用 CommonJS 标准,就像这样

var $ = require('jquery');
require('bootstrap');

由于 Bootstrap 是一个 jQuery 插件,jQuery 会首先加载,而 bootstrap 会在第二个加载。

Babel 允许我使用 ES6 import 语句。但是当我写的时候

import $ from 'jquery';
import Bootstrap from 'bootstrap';

我收到$ is undefined 的错误。 Bootstrap 假设 window.$ 存在,但 import 不会污染窗口对象,这是一件好事,但我的代码是这样的:

// legacy loading for bootstrap
var $ = require('jquery');
window.$ = $;
require('bootstrap');
// the rest of the imports
import _ from 'underscore';

必须有更好的解决方案。任何帮助表示赞赏。

【问题讨论】:

标签: twitter-bootstrap import ecmascript-6


【解决方案1】:

如果您的构建中有Webpack...

...您需要使用 Webpack 的提供插件。由于错误是jQuery is not defined,我们将定义/提供它与插件:

webpack configuration

// webpack.config.js
...
plugins: [
  new webpack.ProvidePlugin({
    jQuery: 'jquery',
    $: 'jquery'
  })
]
...

现在,在我们的ES6/2015 module

// main.js
...
// jquery is required for bootstrap
import $ from 'jquery'

// bootstrap
import 'bootstrap'

// bootstrap css 
import 'bootstrap/dist/css/bootstrap.css'
...

参考:https://2017-sparkler.rhcloud.com/2017/02/01/bootstrap-in-webpack-es6-2015-project/

祝你好运。

【讨论】:

    【解决方案2】:

    引导程序 4 解决方案

    Bootstrap 4 有两个依赖项:jQuery 和 Popper.js

    1. 安装必要的包:

      npm install jquery popper.js bootstrap --save
      
    2. 在您的应用中,像这样导入:

      import 'bootstrap';
      import 'bootstrap/dist/css/bootstrap.css';
      
    3. 如果你想对 jQuery 全局使用 $,请将其添加到你的 webpack 配置中(我是 webpack.base.conf.js):

      plugins: [
        new webpack.ProvidePlugin({
          $: 'jquery'
        })
      ]
      

    【讨论】:

    • 最新的 boostrap 3.* 怎么样?
    【解决方案3】:

    这里的一些答案说要使用 Webpack 的 ProvidePlugin

    截至 2020 年和 bootstrap v4.4.1,您不需要使用该插件。

    Bootstrap 将 jquerypopper.js 定义为对等依赖项,因此您只需将它们与 bootstrap 一起安装即可:

    npm i -S bootstrap jquery popper.js
    
    

    并在您的代码中使用它们,例如:

    import "bootstrap";
    import $ from "jquery";
    
    $(() => {
        $(".element-with-tooltip").tooltip();
    });
    
    

    【讨论】:

      【解决方案4】:

      如果您使用的是Bootstrap 4 alpha,则需要tetherjQuery。此处讨论导入:How to fix the error; 'Error: Bootstrap tooltips require Tether (http://github.hubspot.com/tether/)'

      【讨论】:

        【解决方案5】:
        import './wrappers/jquery';
        import 'bootstrap';
        

        wrappers/jquery.js:

        import jquery from 'jquery;
        window.jQuery = window.$ = jquery;
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2022-10-20
          • 2023-01-19
          • 1970-01-01
          • 2021-06-08
          • 2018-08-22
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多