Thomas Andersen
Thomas Andersen

Reputation: 1529

How can I make webpack skip a require

How can I make webpack skip occurences of

require('shelljs/global');

in my source files? I want to make a bundle of my source files but keep the require('shelljs/global') in the files and not bundle shelljs/global.

Upvotes: 33

Views: 23641

Answers (7)

Jiro Matchonson
Jiro Matchonson

Reputation: 981

If some files contains nested requires and You want to ignore them, You can tell webpack to not do parsing for these specific files. For example if swiper.js and vue-quill-editor.js had inner requires this would be how to ignore them.

module.exports = {
  module: {
    noParse: [
     /swiper.js/,/quill/
    ],

Upvotes: 1

redfox05
redfox05

Reputation: 3692

This should be a last resort option, but if you are certain that your JS file is always parsed by Webpack, and nothing else:

You could replace your require() calls with __non_webpack_require__()

Webpack will parse and convert any occurrence of this and output a normal require() call. This will only work if you are executing in NodeJS OR in a browser if you have a global require library available to trigger.

If webpack does not parse the file, and the script is run by something else, then your code will try to call the non-converted __non_webpack_require__ which will fail. You could potentially write some code that checks earlier in your script if __non_webpack_require__ exists as a function and if not, have it pass the call on to require.

However, this should be temporary, and only to just avoid the build errors, until you can replace it with something like Webpack's own dynamic imports.

Upvotes: 7

Skywalker13
Skywalker13

Reputation: 575

Here a trick

const require = module[`require`].bind(module);

Note the use of a template string

Upvotes: 4

MrBar
MrBar

Reputation: 1106

for new comers, on webpack 2+ the way to do this is like so:

module.exports = {
    entry: __dirname + '/src/app',
    output: {
        path: __dirname + '/dist',
        libraryTarget: 'umd'
    },
    externals: {
        'shelljs/globals': 'commonjs shelljs/global'
    }
};

the bundle will contain a verbatim require:

require('shelljs/global');

read on more supported formats on webpack's config guide and some good examples here

Upvotes: 25

Dmitry  Yaremenko
Dmitry Yaremenko

Reputation: 2580

You can use Ignore Plugin (webpack 1) / Ignore plugin (webpack 2).

Add plugin in webpack.config.js:

plugins: [
  new webpack.IgnorePlugin(/shelljs\/global/),
],

Upvotes: 23

DanV
DanV

Reputation: 3250

If require is in the global namespace and this is why you want Webpack to ignore it, just do window.require()

Upvotes: 7

James Akwuh
James Akwuh

Reputation: 2217

If you store the path in a variable then IgnorePlugin will not work. Though you still could do:

const myCustomModule = eval('require')(myCustomPath)

Upvotes: 37

Related Questions