Open akshaybabajob opened 8 years ago
@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:
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)importType
flag to the webpack-node-externals
configuration (either var
for scripts or amd
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.
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 ascript
tag, or integrate an AMD library likerequire.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)
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)
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
@liady, are there any plans to support something like target: 'web'
in the future?
@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.
@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
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, }, }, }, }, };
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.
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)
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.