[英]ReactJS with Webpack: Uncaught ReferenceError: require is not defined
[英]Webpack ReferenceError: require is not defined (ReactJS)
我了解当在浏览器中调用require()
函数而不是在节点内调用时会发生此错误。 但是,我似乎无法理解我到底需要做什么来解决这个问题。 任何帮助将不胜感激。 您可以转到以下存储库获取整个代码库https://github.com/thegreekjester/React_SSR 。
运行和重现问题的步骤:
localhost:3000
webpack.client.js
const path = require('path');
const webpackNodeExternals = require('webpack-node-externals');
module.exports = {
// production || development
mode: 'development',
// Inform webpack that we're building a bundle
// for nodeJS, rather then for the browser
target: 'node',
// Tell webpack the root file of our
// server application
entry: './src/client.js',
// Tell webpack where to put the output file
// that is generated
output: {
filename: 'client_bundle.js',
path: path.resolve(__dirname, 'build/public'),
publicPath: '/build/public'
},
module: {
rules: [
{
test: /\.js?$/,
loader: 'babel-loader',
exclude: '/node_modules/',
options: {
presets: [
'react', 'stage-0', ['env', {
target: 'web'
}]
]
}
}
]
}
};
webpack.server.js
const path = require('path');
const webpackNodeExternals = require('webpack-node-externals');
module.exports = {
// production || development
mode: 'development',
// Inform webpack that we're building a bundle
// for nodeJS, rather then for the browser
target: 'node',
// Tell webpack the root file of our
// server application
entry: './server.js',
// Tell webpack where to put the output file
// that is generated
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'build'),
publicPath: '/build'
},
module: {
rules: [
{
test: /\.js?$/,
loader: 'babel-loader',
exclude: '/node_modules/',
options: {
presets: [
'react', 'stage-0', ['env', {
target: { browsers: ['last 2 versions']}
}]
]
}
}
]
},
// Tell webpack not to bundle any libraries that exist in the 'node_modules' folder
// into the server bundle
externals: [webpackNodeExternals()]
};
在您的webpack.client.js
,请删除关键target: 'node'
,因为 webpack 捆绑客户端(浏览器)。
在你的webpack.server.js
,请添加一个 key libraryTarget: 'commonjs2'
到output
。 它看起来像这样:
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'build'),
publicPath: '/build',
libraryTarget: 'commonjs2',
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.