webpack - Uncaught ReferenceError : global is not defined at eval

标签 webpack babeljs react-hot-loader babel-polyfill

我遇到了一个我认为是来自 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

我的 webpack 是:

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 中,这是呈现给客户。

这是它在我的 store.js 中的样子:

import thunk from 'redux-thunk';
import logger from 'redux-logger';
import { createStore, applyMiddleware, compose } from 'redux';
import reducers from '../reducers';

export function configureStore(preloadedState) {
    let state;
    const middleware = [thunk, logger];
    const enhancer = compose(applyMiddleware(...middleware));

    if (typeof preloadedState === 'undefined') state = {};
    else state = preloadedState;

    return createStore(reducers, state, enhancer);
}

/**
 Dehydrate (on server)
*/
export function dehydrate(store) {
    return JSON.stringify(store.getState()).replace(/</g, '\\u003c');
}

/**
  Rehydrate (on client)
*/
export function rehydrate() {
    // Grab the state from a global variable injected into the server-generated HTML
    const preloadedState = window.__PRELOADED_STATE__;
    // // Allow the passed state to be garbage-collected
    delete window.__PRELOADED_STATE__;

    return configureStore(preloadedState);
}

如果有的话,这也是我的 .babelrc:

{
    "presets": ["es2015", "react", "stage-0"],
    "env": {
        "development": {
            "plugins": ["react-hot-loader/babel"],
        },
    },
    "plugins": [
        "babel-root-import"
    ],
}

希望任何人都可以帮助解决这个问题——我在研究和试验中还没有找到解决方案。谢谢!

最佳答案

我在非 React 项目中收到了同样的错误消息。我正在构建一个包并使用 karma 在 Chrome 中运行它。解决方案是将我的 webpack 配置从

target: 'node'

target: 'web'

引用:https://webpack.js.org/configuration/target/

关于webpack - Uncaught ReferenceError : global is not defined at eval,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45170267/

相关文章:

reactjs - 运行 webpack-dev-server 时的 VSCode 调试,跳过断点

babeljs - Atom不断抛出babel-eslint错误

reactjs - 如何让react-hot-loader与webpack 2和webpackDevMiddleware一起使用?

javascript - 找不到 .babel 和 React-hot-loader 的正确配置

reactjs - 无法解析模块 'react-dom'

Webpack 报错 Unexpected character '#'

reactjs - 从开发工具中的检查元素查找原始源文件路径

environment-variables - 使用webpack开发和生产环境变量

node.js - Nodemon + babel 多次重启服务器

reactjs - Babel 加载器问题 "You may need an additional loader to handle the result of these loaders" `/@react-spring/web/dist/`