Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude a module from webpack bundle

I'd like the same functionality like RequireJS empty: http://requirejs.org/docs/optimization.html#empty

My use-case is that I include jquery-migrate in development, but I'd like to exclude this when built for production.

Using IgnorePlugin just makes it not included, and when requireing it in the code, it then throws an error (Uncaught Error: Cannot find module "jquery-migrate").

What I'd like to happen is for it to just return undefined, or something of the like (like empty: in RequireJS). Id like to not touch the import in the code, just configuring it to return undefined.

EDIT: Using NormalModuleReplacementPlugin works, if I point the replacement to an empty file. But keeping an empty file around just for this seems unnecessary.

like image 957
SimenB Avatar asked Apr 22 '15 11:04

SimenB


People also ask

What is exclude in Webpack?

Actually, those 'include' and 'exclude' properties are telling the loaders whether to include/exclude the files described (such as the contents of node_modules ), not webpack itself.

Does Webpack bundle Node_modules?

Webpack allows you to define externals - modules that should not be bundled. When bundling with Webpack for the backend - you usually don't want to bundle its node_modules dependencies. This library creates an externals function that ignores node_modules when bundling in Webpack.

What are externals in Webpack?

Webpack externals tell Webpack to exclude a certain import from the bundle. Often externals are used to exclude imports that will be loaded via CDN. For example, suppose you are implementing server-side rendering with Vue and Express, but your client-side code imports Vue via a CDN.

What is bundling in Webpack?

In the wake of React—Facebook's UI library—came Webpack, a simple but awesome module bundler. Module bundlers are just what they are called, they bundle up JavaScript modules into one file. This way, when the client makes a request to your server, it doesn't have to make multiple requests for static files.


2 Answers

I use the null-loader for blanking out modules. The noop-loader can be used for a less awkward if-else in the config.

Try:

rules: [{
    test: /jquery-migrate/,
    use: IS_DEV ? 'null-loader' : 'noop-loader'
}]
like image 50
igl Avatar answered Sep 19 '22 17:09

igl


You can try to make a resolve.alias in webpack.config:

resolve: {
    alias: {
         "jquery-migrate": process.env.NODE_ENV === 'production' ? "empty-module": "jquery-migrate"
    }
}
like image 31
Peter Kese Avatar answered Sep 23 '22 17:09

Peter Kese