[英]Uncaught ReferenceError: require is not defined on webpack setup
I am playing around webpack and react.我在 webpack 周围玩耍并做出反应。
Basically, I have the two files utils.js
and app.js
file sitting under my src
folder.基本上,我的src
文件夹下有两个文件utils.js
和app.js
文件。
Here's the content of my utils.js
file:这是我的utils.js
文件的内容:
const square = (x) => x * x;
export { square };
Here's my app.js
file:这是我的app.js
文件:
import { square } from './utils.js';
console.log('i Hello from app.js here!');
console.log(square(4));
When I run my app via yarn run build
it gave me this error:当我通过yarn run build
运行我的应用程序时,它给了我这个错误:
app.js:3 Uncaught ReferenceError: require is not defined
at app.js:3
I checked out my webpack.config.js
:我检查了我的webpack.config.js
:
const path = require('path');
module.exports = {
entry: './src/app.js',
output: {
path: path.join(__dirname, 'public'),
filename: 'bundle.js'
}
};
I think I am doing good.我觉得我做得很好。 What's wrong with my code?我的代码有什么问题? What does require even means?是什么意思?
You're trying to use a CommonJS module from within your browser.您正在尝试在浏览器中使用 CommonJS 模块。 This will not work.这行不通。 How are you using them?你如何使用它们? When you write import... from... in ES6 Babel will transpile these calls to a module definition called CommonJS and since CommonJS isn't around in the browser you'll get an undefined error from require().当你在 ES6 中编写 import... from... 时,Babel 会将这些调用转换为一个名为 CommonJS 的模块定义,并且由于 CommonJS 不在浏览器中,你会从 require() 中得到一个未定义的错误。 If you want to use CommonJS modules in your code base you need to first bundle them with either Browserify or webpack.如果您想在代码库中使用 CommonJS 模块,您需要首先将它们与 Browserify 或 webpack 捆绑在一起。 The two tools will transform your require calls to some glue magic that you can use within the browser.这两个工具会将您的 require 调用转换为可以在浏览器中使用的一些胶水魔术。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.