【发布时间】:2018-08-27 07:57:04
【问题描述】:
我正在使用 laravel mix 来捆绑我的 js 库和代码。如果可能,我正在尝试使用 ES6 导入样式并使用 ES6 代码。我还需要导入 jQuery 和它的库。
所以,我已经像这样导入了 jQuery 和引导程序:
import "jquery";
import "bootstrap";
起初,当我导入它们时,我得到了:
Uncaught ReferenceError: jQuery is not defined
at Object../node_modules/bootstrap/js/transition.js (vendor.js?id=74f7f0c463b407c6bdf5:2449)
这是由于引导程序没有获取 jQuery。
为了解决这个问题,我添加了这个配置来用 jquery 替换 $, jQuery
mix.webpackConfig(webpack => {
return {
plugins: [
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery',
})
]
};
});
这适用于所有需要 jQuery 的脚本和库。
现在问题在于我们添加的其他脚本没有使用单个 js 或使用刀片部分进行混合。
@section('scripts')
<script type="application/javascript">
window.onload = function() {
if (window.jQuery) {
// jQuery is loaded
console.log("Yeah!");
} else {
// jQuery is not loaded
console.log("Doesn't Work");
}
}
$().ready(function () {
console.log('works');
})
</script>
@endsection
控制台错误显示:
datatables:125 Uncaught ReferenceError: $ is not defined
at datatables:125
(anonymous) @ datatables:125
vendor.js?id=2b5ccc814110031408ca:21536 jQuery.Deferred exception: $(...).uniform is not a function TypeError: $(...).uniform is not a function
at HTMLDocument.<anonymous> (http://localhost/assets/admin/app.js?id=da888f45698c53767fca:18419:18)
at mightThrow (http://localhost/assets/admin/vendor.js?id=2b5ccc814110031408ca:21252:29)
at process (http://localhost/assets/admin/vendor.js?id=2b5ccc814110031408ca:21320:12) undefined
jQuery.Deferred.exceptionHook @ vendor.js?id=2b5ccc814110031408ca:21536
process @ vendor.js?id=2b5ccc814110031408ca:21324
setTimeout (async)
(anonymous) @ vendor.js?id=2b5ccc814110031408ca:21358
fire @ vendor.js?id=2b5ccc814110031408ca:20986
fireWith @ vendor.js?id=2b5ccc814110031408ca:21116
fire @ vendor.js?id=2b5ccc814110031408ca:21124
fire @ vendor.js?id=2b5ccc814110031408ca:20986
fireWith @ vendor.js?id=2b5ccc814110031408ca:21116
ready @ vendor.js?id=2b5ccc814110031408ca:21596
completed @ vendor.js?id=2b5ccc814110031408ca:21606
datatables:122 Doesn't Work
vendor.js?id=2b5ccc814110031408ca:21545 Uncaught TypeError: $(...).uniform is not a function
at HTMLDocument.<anonymous> (app.js?id=da888f45698c53767fca:18419)
at mightThrow (vendor.js?id=2b5ccc814110031408ca:21252)
at process (vendor.js?id=2b5ccc814110031408ca:21320)
当我使用 laravel mix 编译和混合脚本时,问题得到解决,但是当我在刀片中编写相同的脚本或不混合使用时,它显示 jQuery / $ is not defined 错误。
在这种情况下最好的方法是什么?
母版页如下所示:
<body>
@yield('body')
<script src="{{ mix('/assets/admin/manifest.js') }}"></script>
<script src="{{ mix('/assets/admin/vendor.js') }}"></script>
<script src="{{ mix('/assets/admin/app.js') }}"></script>
@section('scripts')
@show
@yield('footer')
</body>
【问题讨论】:
-
感谢配置将 $, jQuery 替换为 jquery。它解决了我缺少 jQuery 的问题。
-
这里一样,它解决了我在 jquery 上使用供应商提取时的问题,但我无法重现您提到的问题(在刀片中运行脚本)。我使用 laravel-mix 2.1.14
标签: jquery laravel laravel-mix