在 Laravel 5.4 Mix 中添加 jQuery

16

我已经熟悉laravel 5.1的mix(elixir),最近我决定测试laravel 5.4的mix。

我将我的库混合在供应商文件中。

mix
.styles([
    './node_modules/bootstrap/dist/css/bootstrap.css',
    './node_modules/font-awesome/css/font-awesome.css'
], 'public/css/vendor.css')
.js([
    './node_modules/jquery/dist/jquery.js',
    './node_modules/bootstrap/dist/js/bootstrap.js',
], 'public/js/vendor.js')
.disableNotifications()
.version();

并在我的页面上包含了供应商。

<script src="{{ mix('js/vendor.js') }}" type="text/javascript" charset="utf-8" async defer></script>
但是,当我想使用jQuery时,我遇到了下面图片中显示的错误。在laravel5.1中,我以前就是这么做的。 enter image description here 我该怎么做?
3个回答

23

只需取消注释您的assets/js/bootstrap.js文件中的此行:

window.$ = window.jQuery = require('jquery');

确保在您的 assets/js/app.js 文件中像这样要求引入 Bootstrap 文件:

require('./bootstrap');

9
mix.autoload({ 'jquery': ['window.$', 'window.jQuery'] })

我需要在我的webpack.mix.js中添加这个。

1
为了让其正常工作,您的资源/资产/js/bootstrap.js 必须被要求(required)。并且以下行必须存在其中。 'window.$ = window.jQuery = require('jquery');' - pat64j
在我看来,这是正确的答案。数组是一组变量的列表,必须完全匹配,才能使Webpack将模块包含在调用它的文件中。例如,Bootstrap不会与答案中的数组一起工作,因为Bootstrap检查变量jQuerywindow.jQueryjQuery不同,必须精确匹配);将jQuery添加到数组中将使Bootstrap正常工作。 - Parziphal
mix.autoload 明显是更好的选择,因为我们正在处理由 Laravel Mix 包装的 Webpack。 - Anadi Misra

2

使用Laravel Mix的解决方案是强制所有模块使用相同的jQuery版本: 这是我在webpack.mix.js顶部的代码:

mix.webpackConfig({
    resolve: {
        alias: {
             'jquery': path.join(__dirname, 'node_modules/jquery/src/jquery')
        }
    }
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接