[英]ReactJS with Webpack: Uncaught ReferenceError: require is not defined
Below is my webpack.config.js. 以下是我的webpack.config.js。 In the browser developer tools, getting "Uncaught ReferenceError: require is not defined" 在浏览器开发人员工具中,获得“未定义的ReferenceError:未定义”
If I remove "target":"node", then error "Uncaught TypeError: fs.readFileSync is not a function" is thrown. 如果删除“目标”:“节点”,则会引发错误“未捕获的TypeError:fs.readFileSync不是函数”。
var config = {
entry: './main.js',
output: {
filename: './index.js',
},
devServer: {
inline: true,
port: 8080
},
node: {
fs: "empty"
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
}
}
]
},
target: 'node'
}
module.exports = config;
You are requiring a native module from node and trying to use it within your browser. 您需要从节点获取本机模块,并尝试在浏览器中使用它。 In this instance you are requiring fs
. 在这种情况下,您需要fs
。
If you are making code for a browser then you are unable to use Nodes fs.readFileSync
and you shouldnt use target: 'node'
如果要为浏览器编写代码,则无法使用Nodes fs.readFileSync
并且fs.readFileSync
使用target: 'node'
I can recreate your problem using the following main.js
file. 我可以使用以下main.js
文件重新创建您的问题。
const fs = require('fs');
const test = function () {
console.log('this is a test');
var contents = fs.readFileSync('DATA', 'utf8');
}
test();
If you are trying to use an additional file within the browser then you either: 如果尝试在浏览器中使用其他文件,则可以:
Require the file on build 需要构建文件
This will permanently ship the data of the file with your index.js file using require
for example. 例如,这将使用require
永久将文件的数据与index.js文件一起发送。 This is perfectly acceptable if the contents is some config and doesnt change per user, examples are language files etc. This method can increase your asset files and hit first time load speeds if the contents on the file is large. 如果内容是一些配置并且每个用户都不会更改,例如语言文件等,则这是完全可以接受的。如果文件上的内容很大,此方法可以增加您的资产文件并达到首次加载速度。
const data = require('some-data.json`)
console.log(data) // would output the JSON
AJAX the content AJAX的内容
Using Ajax/Fetch your could call the contents of the file on page load. 使用Ajax / Fetch可以在页面加载时调用文件的内容。 If this file is meant to be unique for each visitor then you will need to do this. 如果该文件对于每个访问者来说都是唯一的,那么您将需要执行此操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.