“require is not defined” Using webpack 2

前端 未结 3 1636
暗喜
暗喜 2020-12-16 22:23

I\'m having problems with bundle my app using webpack, I\'ve reading in the site similar problems though I\'ve trying all the recommendations and I can\'t figure it out what

相关标签:
3条回答
  • 2020-12-16 23:02

    Hit this issue when building a backend using node + express and a hosted widget for use on the client side. My webpack config is divided into two, one for backend, one for frontend.

    const webpack = require('webpack');
    const path = require('path');
    const nodeExternals = require('webpack-node-externals');
    
    const config = {
      // set to false because __dirname resolving to / instead of absolute path when
      // built using webpack
      node: {
        __dirname: false
      },
      module: {
        rules: [
          {
            test: /\.js$/,
            exclude: /node_modules/,
            use: {
              loader: 'babel-loader',
              options: {
                presets: ['es2015']
              }
            }
          }
        ]
      },
      // set to development to read .env.local variables
      mode: 'development'
    };
    
    const serverConfig = Object.assign({}, config, {
      // set target to node to fix build warnings
      target: 'node',
      name: 'server',
      entry: __dirname + '/src/index.js',
      output: {
        path: path.resolve(__dirname + '/dist'),
        filename: 'index.js'
      },
      // webpack-node-externals package used to exclude other packages like express
      // in the final bundle.js
      externals: [nodeExternals()]
    });
    
    // widget.js file served from dist/widget
    const widgetConfig = Object.assign({}, config, {
      // set target to web for use in browsers
      target: 'web',
      name: 'widget',
      entry: __dirname + '/widget/index.js',
      output: {
        path: path.resolve(__dirname + '/dist/widget/js'),
        filename: 'widget.js'
      }
    });
    
    module.exports = [widgetConfig, serverConfig];
    
    0 讨论(0)
  • 2020-12-16 23:03

    You're using an incorrect target:

    target: 'node'
    

    This means that the bundle is intended to be used in a Node.js (server-side) program, not a browser. You can change it to web, or just remove that line (because web is the default).

    0 讨论(0)
  • 2020-12-16 23:08

    Some of the configuration need to be changed:

    target: 'web', // which is by default // externals: [nodeExternals()], remove this as it is causing problem

    0 讨论(0)
提交回复
热议问题