用ES6导入加载Bootstrap的最佳方法是什么? [英] What is the best way to load Bootstrap with an ES6 import?

查看:35
本文介绍了用ES6导入加载Bootstrap的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I recently switched from using Require.js to using WebPack with Babel. In the past I would use the CommonJS standard in my JS modules, like this

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

由于Bootstrap是jQuery插件,因此jQuery将首先加载,bootstrap将第二加载.

Since Bootstrap is a jQuery plugin, jQuery would load first and bootstrap would load second.

Babel使我可以使用ES6 import 语句.但是当我写

Babel allows me to use ES6 import statements. But when I write

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

我得到一个错误,指出 $未定义.Bootstrap假定存在 window.$ ,但是 import 不会污染窗口对象,这是一件好事,但是让我的代码像这样:

I get the error that $ is undefined. Bootstrap assumes that window.$ is present, but import does not pollute the window object, which is a good thing, but leaves my code like this:

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

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

There must be a better solution. Any help appreciated.

推荐答案

如果您的构建中包含 Webpack ...

...您需要使用 Webpack的提供插件.由于错误是未定义 jQuery ,我们将使用插件定义/提供:

If you have Webpack in your build...

...you'll need to work with Webpack's provide plugin. Since the error is that jQuery is not defined we will define/provide it with the plugin :

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

现在,在我们的 ES6/2015模块中:

// 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/

祝你好运.

这篇关于用ES6导入加载Bootstrap的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆