如何在ES6中调用bootstrap's jQuery插件

How to call bootstrap's jQuery plugins in ES6

本文关键字:jQuery 插件 bootstrap ES6 调用      更新时间:2023-09-26

我试图调用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,但在那之后我不确定我必须导入哪个节点模块(就像你可以在导入的注释行中看到的那样)。所以,我想直接导入bootstrap.min.js .

事实是,我仍然有一个错误(独立,如果我尝试与弹出窗口/模式/工具提示)像这样在我的app.js,这是我的javascript从webpack生成:

Uncaught TypeError: (0 , _jquery2.default)(...).tooltip is not a function
就像我说的,我被困在这里了。

最后,bootstrap 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']);
});

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

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

这个插件实际上会在任何其他请求他的模块中注入'jquery'模块(意思是,每个使用jquery或$或window.jQuery对象的模块),bootstrap就是其中之一。