webpack-node-externals
webpack-node-externals copied to clipboard
Uncaught ReferenceError: require is not defined
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 can you please share your webpack config?
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)); }
I have the same issue, any updates?
@ericraio Can you share the node stack trace for this exception?
Same issue. This is targeting the browser.
Using libraryTarget: 'umd'
:
Using default libraryTarget
:
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'
}
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:
- (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) - Have the external modules loaded in some other way in the browser, and add the appropriate
importType
flag to thewebpack-node-externals
configuration (eithervar
for scripts oramd
for AMD)
Same issue and @liady didn't solve it
@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)
i can't solve "require is not defined" !!!!!!!! can you tell me you are successor? @liady
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': {}
})
]
};
@anlexN can you solve it?
now , i give up this issue. it is a webpack bug.
@anlexN ok,thanks.
Any update? I am also getting the same issue
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.
Still having the same issue. Any solution for this one?
Having the same issue. @liady
Same here. @liady
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.
I think we must update webpack version
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 I'm not sure why, but you can probably resolve it by removing target: 'node'
from webpack configuration
As per @liady's comment I solved my problem by removing the use of nodeExternals
in the client webpack config 🙌
I have the same problem. Nobody can solve it?
@thucng I'm not sure why, but you can probably resolve it by removing
target: 'node'
from webpack configuration it works!
@thucng I'm not sure why, but you can probably resolve it by removing
target: 'node'
from webpack configuration
Thanks, it works for me!!
Change the target
property to browser
, it worked as well.
target: 'web'
target: 'web'
results in the same require is not defined
error.
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.
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.