webpack-node-externals icon indicating copy to clipboard operation
webpack-node-externals copied to clipboard

Uncaught ReferenceError: require is not defined

Open akshaybabajob opened this issue 7 years ago • 38 comments

When I add this to my commonconfig in webpack, it throws this error. I can't understand why is it occurring or how to solve this. Any help will be appreciated.

akshaybabajob avatar Nov 09 '16 19:11 akshaybabajob

@akshaybabajob can you please share your webpack config?

liady avatar Nov 09 '16 23:11 liady

var webpack = require('webpack'); var path = require('path'); var clone = require('js.clone'); var resolveNgRoute = require('@angularclass/resolve-angular-routes'); var ExtractTextPlugin = require("extract-text-webpack-plugin"); var CompressionPlugin = require("compression-webpack-plugin"); var nodeExternals = require('webpack-node-externals');

var commonPlugins = [ new webpack.ContextReplacementPlugin( // The (|/) piece accounts for path separators in *nix and Windows /angular(|/)core(|/)src(|/)linker/, root('./src'), { // your Angular Async Route paths relative to this root directory } ), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } }), new CompressionPlugin({ asset: "[path].gz[query]", algorithm: "gzip", //test: /.js$|.css$|.html$/, test: /.js$|.css$|.html$/, threshold: 10240, minRatio: 0.8 }) ];

var commonConfig = { resolve: { extensions: ['', '.ts', '.js', '.json'] }, context: __dirname, output: { publicPath: path.resolve(__dirname), filename: 'index.js' }, //externals: /^[^@.]/, externals: [nodeExternals()], devtool: 'cheap-module-eval-source-map', module: { loaders: [ // TypeScript { test: /.ts$/, loaders: ['ts-loader', 'angular2-template-loader'] }, { test: /.html$/, loader: 'raw-loader' }, { test: /.css$/, loader: ['raw-loader','css-loader']}, { test: /.json$/, loader: 'json-loader' }, { test: /.scss$/, exclude: /node_modules/, //loader: []'to-string!css-loader!postcss-loader!sass-loader' loader: ['css-loader','postcss-loader','sass-loader'] } ], },

postcss: [ require('postcss-cssnext')({ browsers: ['ie >= 9', 'last 2 versions'] }) ],

};

var clientConfig = { target: 'web', entry: './src/client', output: { path: root('dist/client') }, devtool: 'cheap-module-eval-source-map', node: { global: true, __dirname: true, __filename: true, process: true, Buffer: false } };

var serverConfig = { target: 'node', entry: './src/server', // use the entry file of the node server if everything is ts rather than es5 output: { path: root('dist/server'), libraryTarget: 'commonjs2' }, module: { preLoaders: [ { test: /angular2-material/, loader: "imports-loader?window=>global" } ], }, externals: includeClientPackages([ // include these client packages so we can transform their source with webpack loaders '@angular2-material/button', '@angular2-material/button', '@angular2-material/card', '@angular2-material/checkbox', '@angular2-material/core', '@angular2-material/grid', '@angular2-material/icon', '@angular2-material/input', '@angular2-material/list', '@angular2-material/menu', '@angular2-material/progress', '@angular2-material/progress', '@angular2-material/radio', '@angular2-material/sidenav', '@angular2-material/slider', '@angular2-material/slide', '@angular2-material/tabs', '@angular2-material/toolbar', '@angular2-material/tooltip' ]), node: { global: true, __dirname: true, __filename: true, process: true, Buffer: true } };

// Default config // var defaultConfig = { // context: __dirname, // resolve: { // root: root('/src') // }, // output: { // publicPath: path.resolve(__dirname), // filename: 'index.js' // }, // // };

// Server. var serverPlugins = [

];

// Client. var clientPlugins = [

];

var webpackMerge = require('webpack-merge'); module.exports = [ // Client webpackMerge(clone(commonConfig), clientConfig, { plugins: clientPlugins.concat(commonPlugins) }),

// Server webpackMerge(clone(commonConfig), serverConfig, { plugins: serverPlugins.concat(commonPlugins) })

//TODO : Test add this test cases file //webpackMerge({}, defaultConfig, commonConfig, testConfig) ];

function includeClientPackages(packages) { return function(context, request, cb) { if (packages && packages.indexOf(request) !== -1) { return cb(); } return checkNodeImport(context, request, cb); }; } // Helpers function checkNodeImport(context, request, cb) { if (!path.isAbsolute(request) && request.charAt(0) !== '.') { cb(null, 'commonjs ' + request); return; } cb(); }

function root(args) { args = Array.prototype.slice.call(arguments, 0); return path.join.apply(path, [__dirname].concat(args)); }

akshaybabajob avatar Nov 10 '16 06:11 akshaybabajob

I have the same issue, any updates?

ericraio avatar Nov 26 '16 05:11 ericraio

@ericraio Can you share the node stack trace for this exception?

liady avatar Nov 27 '16 13:11 liady

Same issue. This is targeting the browser.

Using libraryTarget: 'umd': screen shot 2017-01-28 at 8 10 25 pm

Using default libraryTarget: screen shot 2017-01-28 at 8 11 25 pm

Config:

var nodeExternals = require('webpack-node-externals')

module.exports = {
  entry: './src/index.js',
  output: {
    path: 'dist',
    filename: 'index.js'
  },
  externals: [nodeExternals()],
  module: {
    loaders: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel'
      }
    ]
  },
  devtool: 'source-map'
}

AndersDJohnson avatar Jan 29 '17 02:01 AndersDJohnson

Notice that webpack-node-externals is meant mainly for excluding node modules when building for a library for Node. It leaves the require(...) statements, instead of bundling them. require is a Node function, so when running in a Node environment it knows to fetch this module.

When running the code in the browser, there is no builtin require function. If you want to flag a module as external in the browser, you have to provide some other way to load it (put a script tag, or integrate an AMD library like require.js). Otherwise this external module cannot be imported.

There are 2 ways to solve the issue:

  1. (Recommended) Don't activate webpack-node-externals in your Webpack browser config, but let Webpack indeed bundle those modules when targeting the web (this is probable what you want to do)
  2. Have the external modules loaded in some other way in the browser, and add the appropriate importType flag to the webpack-node-externals configuration (either var for scripts or amd for AMD)

liady avatar Mar 05 '17 11:03 liady

Same issue and @liady didn't solve it

abdifardin avatar May 06 '17 05:05 abdifardin

@FakhruddinAbdi Are you running your bundle in the browser? webpack-node-externals with the default configuration produces bundles that are suitable for commonjs environements (e.g Node)

liady avatar May 08 '17 09:05 liady

i can't solve "require is not defined" !!!!!!!! can you tell me you are successor? @liady

anlexN avatar May 20 '17 03:05 anlexN

Have same :

	const path = require('path'); <-- this line :/
	const webpack = require('webpack');

	module.exports = {
		entry: './src/index.js',
		output: {
			filename: 'bundle.js',
			path: path.resolve(__dirname, 'dist')
		},
		target: "node",
		module: {
		loaders: [
			{
				test: /\.(js|jsx)$/,
				loaders: 'babel-loader',
				exclude: /node_modules/,
				query: {
					presets: ['es2015']
				}
			}
			]
		},
		stats: {
			colors: true
		},
		devtool: 'source-map',
		plugins: [
			new webpack.DefinePlugin({
				'process.env': {}
			})
		]
	};

darkiron avatar Oct 25 '17 13:10 darkiron

@anlexN can you solve it?

snoop-dog avatar Mar 15 '18 03:03 snoop-dog

now , i give up this issue. it is a webpack bug.

anlexN avatar Mar 15 '18 07:03 anlexN

@anlexN ok,thanks.

snoop-dog avatar Mar 15 '18 08:03 snoop-dog

Any update? I am also getting the same issue

thomascrown avatar Mar 21 '18 21:03 thomascrown

I had rules for script-loader in my webpack.config.js

{test: /.js$/, use:['script-loader'] }

Removing this from webpack.config.js rmoved the error.

dheerajsk avatar Mar 28 '18 12:03 dheerajsk

Still having the same issue. Any solution for this one?

mkotsollaris avatar Apr 29 '18 20:04 mkotsollaris

Having the same issue. @liady

bengrunfeld avatar May 09 '18 01:05 bengrunfeld

Same here. @liady

ghost avatar Jun 26 '18 16:06 ghost

This tool is not meant for webpack projects that run in the browser. The author cannot help any of you because you are using this library in the wrong environment.

stevenpetryk avatar Sep 18 '18 23:09 stevenpetryk

I think we must update webpack version

KLadnany avatar Oct 09 '18 16:10 KLadnany

I have the same issue, any updates?

My config webpack


const server = {
  target: 'node',
  externals: [nodeExternals()],
  entry: [
    paths.appServerJs,
  ],
  output: {
    pathinfo: true,
    filename: 'static/js/bundle.js',
    chunkFilename: 'static/js/[name].chunk.js',
    publicPath: publicPath,
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx|mjs)$/,
        loader: require.resolve('source-map-loader'),
        enforce: 'pre',
        include: paths.appSrc,
      },
      {
        test: /\.(js|jsx|mjs)$/,
        include: paths.appSrc,
        loader: require.resolve('babel-loader'),
        options: {
          
          compact: true,
        },
      },

      // Compile .tsx?
      {
        test: /\.(ts|tsx)$/,
        include: paths.appSrc,
        use: [
          {
            loader: require.resolve('ts-loader'),
            options: {
              // disable type checker - we will use it in fork plugin
              transpileOnly: true,
            },
          },
        ],
      },
    ],
  },
  plugins: [
    new InterpolateHtmlPlugin(env.raw),
    new HtmlWebpackPlugin({
      inject: true,
      template: paths.appHtml,
    }),
  ],
}
module.exports = server

thucng avatar Jan 14 '19 10:01 thucng

@thucng I'm not sure why, but you can probably resolve it by removing target: 'node' from webpack configuration

idanavr avatar Jan 18 '19 10:01 idanavr

As per @liady's comment I solved my problem by removing the use of nodeExternals in the client webpack config 🙌

pjlee11 avatar Jan 24 '19 13:01 pjlee11

I have the same problem. Nobody can solve it?

Vibing avatar Jun 09 '19 10:06 Vibing

@thucng I'm not sure why, but you can probably resolve it by removing target: 'node' from webpack configuration it works!

SusanLiu3 avatar Jun 25 '19 13:06 SusanLiu3

@thucng I'm not sure why, but you can probably resolve it by removing target: 'node' from webpack configuration

Thanks, it works for me!!

yaololo avatar Jan 11 '20 08:01 yaololo

Change the target property to browser, it worked as well.

target: 'web'

techyaura avatar Feb 29 '20 19:02 techyaura

target: 'web' results in the same require is not defined error.

jerryji avatar Apr 11 '20 13:04 jerryji

I was able to resolve is sort of issue with webpack:

target: 'web',
externals: ["fs"],

Full disclosure I have not tried it with this package.

matt-antone avatar Apr 23 '20 21:04 matt-antone

I get this error when I run NODE_ENV=development webpack (but not in Google Chrome). I DON'T get this error in Edge / Firefox when I run NODE_ENV=production webpack

Not sure if that helps.

zachsa avatar May 11 '20 15:05 zachsa