我刚开始使用 laravel mix 和 Yarn(来自 Codekit),所以请耐心等待!我的项目中有我的 webpack.mix.js
文件,如下所示:
const mix = require('laravel-mix');
const tailwindcss = require('tailwindcss');
const purgeCss = require('laravel-mix-purgecss');
mix.postCss('./source/styles/styles.css', './public/assets/css/', [
tailwindcss('./tailwind.js'),
]);
mix.scripts([
'./source/scripts/app.js',
], './public/assets/js/app.js');
mix.copyDirectory('./source/fonts', './public/assets/fonts');
mix.copy('./source/images/', './public/assets/img/');
mix.copy('./source/root_files/', './public/');
mix.purgeCss({
enabled: true,
globs: [
path.join(__dirname, './public/*.html'),
path.join(__dirname, './public/assets/*.js'),
],
extensions: ['html', 'js', 'php'],
});
mix.browserSync({
proxy: 'something.loc',
files: [ './public/*.html', './public/assets/**/*.*' ]
});
目前工作正常,可以做我想做的一切。
现在我想添加 lodash.debounce
和 lodash.throttle
,以便我可以在 app.js
文件中使用这些函数。我已使用 yarn add
将它们添加到我的项目中,它们位于我的 node_modules
文件夹中。
我的问题是我接下来该怎么做?我尝试从 node_modules
文件夹添加 index.js
文件,如下所示:
mix.scripts([
'./node_modules/lodash.debounce/index.js',
'./source/scripts/app.js',
], './public/assets/js/app.js');
这是使用yarn dev
构建的,但随后我在页面上收到控制台错误:ReferenceError:模块未定义
我对这种工作方式很陌生,所以这可能是显而易见的事情,感谢您的帮助!
更新
我现在尝试在我的 webpack.mix.js
文件中使用以下内容:
mix.js('./source/scripts/app.js', './public/assets/js/app.js');
并将其添加到我的 /source/scripts/app.js
文件中:
const debounce = require('lodash.debounce');
const throttle = require('lodash.throttle');
window.onresize = _.debounce(() => {
console.log('resized!')
}, 100)
当我构建并打开控制台时,我收到此错误:
ReferenceError: _ is not defined
最佳答案
您应该在 source/scripts/app.js
文件中使用 require
。这通常是您应该对通过 Yarn 添加的任何 JavaScript 模块执行的操作。
// source/scripts/app.js
const debounce = require('lodash.debounce');
const throttle = require('lodash.throttle');
你所得到的是告诉laravel-mix
你的应用程序有两个入口点。当它尝试将这些文件转换为单个包时,它不知道如何处理 lodash 依赖项内的 module.exports 语句,因此它只是将其留在那里,因此会出现浏览器控制台错误。
关于javascript - 如何使用 Laravel Mix 将 lodash debounce 添加到我的项目中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55049029/