简体   繁体   中英

Uncaught ReferenceError: require is not defined - Webpack2

I'm updating an app to use webpack 2 from webpack 1 and the regular build works fine. The issue seems to arise when using the devServer and requiring just one of the chunks generated (it's an electron app so I have main and renderer chunks - both are included in a regular build, and with the dev server only the renderer chunk is included)

Everything worked on webpack 1, but for some reason the runtime isn't being included in my chunks? I've tried reordering them but to no avail.

const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
const path = require('path');

module.exports = {
  context: __dirname,
  entry: {
    main: './main.js',
    renderer: './app/index.jsx'
  },
  output: {
      path: path.resolve(__dirname, './dist'),
      filename: "[name].js"
  },
  node: {
    __dirname: false,
    __filename: false
  },
  devtool: 'cheap-eval-source-map',
  target: 'electron',
  module: {
    loaders: [
      {
        test: /(\.js$|\.jsx$)/,
        exclude: /(node_modules|dist)/,
        loader: 'babel'
      },
      { test: /\.scss$/, loader: "style!css?modules!sass" },
      { test: /\.png$/, loader: "url?limit=100000" },
      { test: /\.jpg$/, loader: "file" }
    ]
  },
  resolve: {
    extensions: ['.js', '.jsx', '.scss'],
    modules: [path.resolve('./app'), 'node_modules']
  },
  plugins: [
  new HtmlWebpackPlugin({
    template: './app/index.html',
    chunks: ['renderer'],
    inject: 'body',
    hash: 'true'
  }),
  new webpack.DefinePlugin({
      'process.env': {
        'NODE_ENV': '"dev"'
      }
    })
  ],
  devServer: {
    contentBase: __dirname
  },
  externals: {
    'cheerio': 'window',
    'react/addons': true,
    'react/lib/ExecutionEnvironment': true,
    'react/lib/ReactContext': true
  }
};

It seems one of the chunks isn't included properly:

/***/ },
/* 26 */
/***/ function(module, exports) {

module.exports = require("url");

Why is this?

So it seems the issue was with me setting the target to electron but building for web. This seemed to work in webpack 1, but after updating to webpack 2 it no longer includes the runtime in both bundles.

The solution I took was to have two configs - one for electron (my main build), and one for web (specify the target in the webpack config)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM