Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Uncaught ReferenceError: require is not defined #17

Open
akshaybabajob opened this issue Nov 9, 2016 · 38 comments
Open

Uncaught ReferenceError: require is not defined #17

akshaybabajob opened this issue Nov 9, 2016 · 38 comments

Comments

@akshaybabajob
Copy link

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.

@liady
Copy link
Owner

liady commented Nov 9, 2016

@akshaybabajob can you please share your webpack config?

@akshaybabajob
Copy link
Author

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));
}

@ericraio
Copy link

I have the same issue, any updates?

@liady
Copy link
Owner

liady commented Nov 27, 2016

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

@AndersDJohnson
Copy link

AndersDJohnson commented Jan 29, 2017

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'
}

@liady
Copy link
Owner

liady commented Mar 5, 2017

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 liady closed this as completed Mar 5, 2017
@liady liady reopened this Mar 5, 2017
@abdifardin
Copy link

Same issue and @liady didn't solve it

@liady
Copy link
Owner

liady commented May 8, 2017

@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)

@anlexN
Copy link

anlexN commented May 20, 2017

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

@darkiron
Copy link

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': {}
			})
		]
	};

@qilinjie1124
Copy link

@anlexN can you solve it?

@anlexN
Copy link

anlexN commented Mar 15, 2018

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

@qilinjie1124
Copy link

@anlexN ok,thanks.

@thomascrown
Copy link

Any update? I am also getting the same issue

@dheerajsk
Copy link

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.

@mkotsollaris
Copy link

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

@bengrunfeld
Copy link

bengrunfeld commented May 9, 2018

Having the same issue. @liady

@ghost
Copy link

ghost commented Jun 26, 2018

Same here. @liady

@stevenpetryk
Copy link

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.

@KLadnany
Copy link

KLadnany commented Oct 9, 2018

I think we must update webpack version

@thucng
Copy link

thucng commented Jan 14, 2019

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

@idanavr
Copy link

idanavr commented Jan 18, 2019

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

@pjlee11
Copy link

pjlee11 commented Jan 24, 2019

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

@Vibing
Copy link

Vibing commented Jun 9, 2019

I have the same problem. Nobody can solve it?

@SusanLiu3
Copy link

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

@yaololo
Copy link

yaololo commented Jan 11, 2020

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

Thanks, it works for me!!

@techyaura
Copy link

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

target: 'web'

@jerryji
Copy link

jerryji commented Apr 11, 2020

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

@matt-antone
Copy link

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.

@zachsa
Copy link

zachsa commented May 11, 2020

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.

@RedTn
Copy link

RedTn commented May 29, 2020

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)

adding that #2 worked for me, im writing a web app but another system was doing the webpack bundling for me, adding
options.importType = function (moduleName) { return 'amd ' + moduleName; }
worked since it was using amd and not commonjs (commonjs being default)

@vokidya
Copy link

vokidya commented Jun 13, 2020

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

My issue solved by removing nodeExternals

@iorrah
Copy link

iorrah commented Jul 15, 2020

@liady, are there any plans to support something like target: 'web' in the future?

@liady
Copy link
Owner

liady commented Jul 15, 2020

@iorrah Thank you for your question!
The main purpose of this library is handling cases when a code is bundled to be used in a Node environment.
In this case - its dependencies don't need to be bundled, but can be left as require calls (since the code is running in a Node environment).
However - when running in a web environment - all the dependencies must be bundled as well (there are no sync require calls in the browser) - so using this library will actually not make sense.
Please let me know if you see a use case (for the browser) that I may have missed.

@iorrah
Copy link

iorrah commented Jul 15, 2020

@liady, thank you for your answer. My use case is: when using webpack-node-externals to generate separated bundles (codebase and vendors), something causes loaders as Babel to stop working -- I mean, it's a node_module after all, right? A target: 'web' option would tell webpack-node-externals to not see loaders as something external, since they are essential for the web build.

I want to create a webpack bundle containing only my codebase (which is a massive react app), and afterwards an individual vendors bundle containing only my vendors.

Errors showing up on Chrome console:

external "react":1 Uncaught ReferenceError: require is not defined
    at Object.react (external "react":1)
    at __webpack_require__ (bootstrap:832)
    at fn (bootstrap:129)
    at Object../src/module/index.js (index.js:4)
    at __webpack_require__ (bootstrap:832)
    at bootstrap:970
    at bootstrap:970

@mallikarjuna-sharma
Copy link

when i un comment externals: [webpackNodeExternals()], it is working but this plugin is not working .. anyone help ..

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const webpackNodeExternals = require("webpack-node-externals");
const uglifyJSPlugin = require("uglifyjs-webpack-plugin");

const devMode = process.env.NODE_ENV !== "production";

module.exports = {
entry: path.resolve(__dirname, "./src/index.tsx"),
output: {
filename: "[name].bundle.js",
path: path.resolve(__dirname, "build"),
publicPath: "/",
},
devServer: {
historyApiFallback: true,
port: 4001,
contentBase: "/build",
writeToDisk: true,
publicPath: "/",
},
devtool: "source-map",
module: {
rules: [
{
test: /.(ts|tsx)$/,
enforce: "pre",
use: [
{
options: {
eslintPath: require.resolve("eslint"),
},
loader: require.resolve("eslint-loader"),
},
],
exclude: /node_modules/,
},
{
test: /.tsx?$/,
loader: "ts-loader",
exclude: /node_modules|.d.ts$/,
options: {
configFile: path.resolve("./tsconfig.json"),
},
},
{
test: /.d.tsx?$/,
loader: "ts-loader",
exclude: /node_modules/,
options: {
configFile: path.resolve("./tsconfig.json"),
},
},
{
test: /.jsx?$/,
loader: "babel-loader",
},
{
test: /.css$/,
use: [devMode ? "style-loader" : MiniCssExtractPlugin.loader, "css-loader"],
},
{
test: /.(png|jpe?g|svg)$/,
loader: "file-loader",
options: {
publicPath: "/",
},
},
],
},
resolve: {
extensions: [".js", ".ts", ".tsx", ".css", ".d.ts"],
modules: [path.resolve("node_modules"), path.resolve(__dirname, "./src")],
},
plugins: [
new HtmlWebpackPlugin({
template: "./public/index.html",
}),
],
// externals: [webpackNodeExternals()],
optimization: {
minimizer: [
new uglifyJSPlugin({
uglifyOptions: {
sourceMap: true,
},
}),
],
runtimeChunk: "single",
splitChunks: {
cacheGroups: {
default: false,
commons: {
chunks: "all",
test: /[\/]node_modules[\/]/,
name: "vendors",
enforce: true,
minChunks: 2,
},
},
},
},
};

@jakeeis
Copy link

jakeeis commented Mar 21, 2021

I just ran into this issue due to having "type": "module" in my package.json. Removing that and changing my filetypes from ".js" to ".mjs" seemed to fix it.

@eduardolima1994
Copy link

I have the same error!

bundle.js:1707 Uncaught ReferenceError: require is not defined
at Object.events (bundle.js:1707)
at webpack_require (bundle.js:2000)
at fn (bundle.js:2153)
at eval (emitter.js:1)
at Object../node_modules/webpack/hot/emitter.js (bundle.js:1643)
at webpack_require (bundle.js:2000)
at fn (bundle.js:2153)
at eval (dev-server.js:50)
at Object../node_modules/webpack/hot/dev-server.js (bundle.js:1633)
at webpack_require (bundle.js:2000)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests