liady / webpack-node-externals

Easily exclude node modules in Webpack
MIT License
1.29k stars 62 forks source link

Uncaught ReferenceError: require is not defined #17

Open akshaybabajob opened 8 years ago

akshaybabajob commented 8 years ago

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 commented 8 years ago

@akshaybabajob can you please share your webpack config?

akshaybabajob commented 8 years ago

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 commented 7 years ago

I have the same issue, any updates?

liady commented 7 years ago

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

AndersDJohnson commented 7 years ago

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 commented 7 years ago

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)
abdifardin commented 7 years ago

Same issue and @liady didn't solve it

liady commented 7 years ago

@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 commented 7 years ago

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

darkiron commented 7 years ago

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 commented 6 years ago

@anlexN can you solve it?

anlexN commented 6 years ago

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

qilinjie1124 commented 6 years ago

@anlexN ok,thanks.

thomascrown commented 6 years ago

Any update? I am also getting the same issue

dheerajsk commented 6 years ago

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 commented 6 years ago

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

bengrunfeld commented 6 years ago

Having the same issue. @liady

ghost commented 6 years ago

Same here. @liady

stevenpetryk commented 6 years ago

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 commented 6 years ago

I think we must update webpack version

thucng commented 5 years ago

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 commented 5 years ago

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

pjlee11 commented 5 years ago

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

Vibing commented 5 years ago

I have the same problem. Nobody can solve it?

SusanLiu3 commented 5 years ago

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

yaololo commented 4 years ago

@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 commented 4 years ago

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

target: 'web'

jerryji commented 4 years ago

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

matt-antone commented 4 years ago

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 commented 4 years ago

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 commented 4 years ago

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 commented 4 years ago

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 commented 4 years ago

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

liady commented 4 years ago

@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 commented 4 years ago

@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 commented 4 years ago

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 commented 3 years ago

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 commented 3 years ago

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)