我遇到了一个错误,我认为是来自webpack的。
index.js:9 Uncaught ReferenceError: global is not defined
at eval (index.js:9)
at Object.<anonymous> (bundle.js:2548)
at __webpack_require__ (bundle.js:622)
at fn (bundle.js:48)
at eval (client:1)
at Object.<anonymous> (bundle.js:2541)
at __webpack_require__ (bundle.js:622)
at bundle.js:668
at bundle.js:671
我的网络包是:
import webpack from 'webpack';
import merge from 'webpack-merge';
import path from 'path';
import isDev from 'isdev';
import { Dir } from './src/utils';
const TARGET = process.env.npm_lifecycle_event;
let Config = {
entry: [
'babel-polyfill',
'react-hot-loader/patch',
path.join(Dir.src, 'client.js'),
],
output: {
path: path.join(Dir.public, 'build'),
filename: 'bundle.js',
},
target: 'node',
resolve: {
modules: [Dir.src, 'node_modules'],
extensions: ['*', '.js', '.jsx', '.json'],
},
module: {
rules: [
{
test: /\.js?$/,
enforce: 'pre',
loader: 'eslint-loader',
exclude: /node_modules/,
include: Dir.src,
},
{
test: /\.js?$/,
loader: 'babel-loader',
exclude: /node_modules/,
},
],
},
plugins: [
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify(process.env.NODE_ENV),
},
}),
],
};
if (TARGET === 'build:prod' && !isDev) {
Config = merge(Config, {
bail: true,
devtool: 'source-map',
output: { publicPath: '/build/' },
plugins: [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin({
comments: false,
dropDebugger: true,
dropConsole: true,
compressor: {
warnings: false,
},
}),
],
});
}
if (TARGET === 'server:dev' && isDev) {
Config = merge(Config, {
devtool: 'eval',
entry: ['webpack-hot-middleware/client'],
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
],
});
}
const WebpackConfig = Config;
export default WebpackConfig;
这个错误只有在我添加了Redux建议的服务器端渲染后才开始出现。所以我使用了商店水合,其中有./src/utils/store.js中的window.PRELOADED_STATE,它也在index.ejs中,这是渲染到客户端的文件。
这也是我的.babelrc如果有的话:
{
"presets": ["es2015", "react", "stage-0"],
"env": {
"development": {
"plugins": ["react-hot-loader/babel"],
},
},
"plugins": [
"babel-root-import"
],
}
希望任何人都可以帮助这个-我还没有找到一个解决方案,在我的研究和试验。谢谢!
2条答案
按热度按时间vfh0ocws1#
问题是,我认为,在您的webpack.config.js中的这个
target: 'node'
。这基本上说明Webpack可能假设bundle将在一个类似节点的环境中运行,其中像global
和require
这样的全局变量是由环境提供的。除非另有说明,Webpack假定浏览器环境并重写global
以指向window
。您的配置禁用此重写。您可以从配置中删除
target: 'node'
,或者通过将node: {global: true}
添加到配置对象来显式启用global
重写。mkshixfv2#
我有这个问题。开玩笑的,我加了
--env='jsdom'
。在
"test":"react-scripts test ...."
的packages.json
、scripts:
部分中,我添加了--env='jsdom'
,因为新的默认值为--env='node'
"test":"react-scripts test --env='jsdom' ... "