【问题标题】:How to call bootstrap's jQuery plugins in ES6如何在 ES6 中调用 bootstrap 的 jQuery 插件
【发布时间】:2016-08-24 15:33:42
【问题描述】:

我一直在尝试调用 bootstrap 的 jQuery 插件,例如弹出框、工具提示、模式...

我正在使用 webpack,这是我的 ES6 javascript:

import $ from 'jquery';
//import Bootstrap from 'bootstrap-sass';
//import Bootstrap from 'bootstrap-loader';
import Bootstrap from '../vendor/bootstrap.min.js';

class Test {
    constructor () {
        $('[data-toggle="tooltip"]').tooltip({ html: true });
    }
}

我尝试使用 npm 安装引导程序,但之后我不确定我必须导入哪个节点模块(就像您在导入的注释行中看到的那样)。所以,我想直接导入bootstrap.min.js。

事实是我在我的app.js 中仍然有这样的错误(如果我尝试使用 popover/modals/tooltip),这是我从 webpack 生成的 javascript:

Uncaught TypeError: (0 , _jquery2.default)(...).tooltip is not a function

就像我说的,我被困在这里了。

最后,boostrap CSS 可以正常工作,这要归功于:

gulp.task('bootstrap-fonts', function() {
    return gulp.src('node_modules/bootstrap-sass/assets/fonts/bootstrap/*')
  .pipe(gulp.dest('./app/assets/fonts/bootstrap'));
});

gulp.task('dev', ['css', 'bootstrap-fonts', 'browser-sync', 'webpack'], function () {
    gulp.watch('src/scss/**/*.scss', ['css']);
    gulp.watch('src/js/**/*.js', ['webpack']);
    gulp.watch('app/*.html', ['bs-reload']);
});

【问题讨论】:

    标签: javascript twitter-bootstrap ecmascript-6 webpack html5boilerplate


    【解决方案1】:

    因为引导库依赖于 jQuery, 您应该尝试将以下插件添加到 webpack.config.js 中的 'plugins' 数组中,以便引导模块将使用 jQuery 全局对象:

    new webpack.ProvidePlugin({
        $: "jquery",
        jQuery: "jquery",
        "window.jQuery": 'jquery'
    }),
    

    这个插件实际上会在需要他的任何其他模块中注入“jquery”模块(意味着,每个使用对象 jQuery 或 $ 或 window.jQuery 的模块),而 bootstrap 就是其中之一。

    【讨论】:

    • 不够import $ from 'jquery' ?
    • 不,因为你刚刚在这个当前文件(这个当前模块)中导入了“jquery”,所以现在只有这个文件“知道”什么是“jquery”。但引导程序自己使用的是全局 jQuery 对象。这是 webpack 让 bootstrap 知道 jQuery 对象的方式
    • @Jumpa 对其他库也一样吗?假设我有 2 个组件需要 library.js。你认为将它放在全局范围内比导入两次(每个组件一次)更好吗?
    • @JohnnyQ 不一样。在您的情况下,我会两次导入 library.js 模块(在每个需要他的模块中)。我谈到了依赖于另一个 3rd 方库的 3rd 方库(实际上是依赖于一个全局对象,例如依赖 jQuery 的 bootstrap)
    • 谢谢!多次导入模块比导入更好的任何原因是全局的?
    猜你喜欢
    • 1970-01-01
    • 2016-10-30
    • 1970-01-01
    • 2018-01-03
    • 1970-01-01
    • 2017-09-24
    • 2010-11-17
    • 2010-11-05
    • 2014-09-01
    相关资源
    最近更新 更多