How to exclude a module from webpack, and instead import it using es6

20.7k Views Asked by At

I am currently using webpack to bundle up a javascript file with react. This file also has another import statement to another module within my project

import { MyModule} from './MyModuleFile.js'

Is there a way to exclude MyModule.js from the webpack bundle, and instead keep the import as is?

2

There are 2 best solutions below

1
On

Just add it to the exclude option in your loader configuration of your webpack.config.js:

rules: [
  // rules for modules (configure loaders, parser options, etc.)
  {
    test: /\.js$/,
    exclude: [
      /node_modules/,
      /MyModuleFile/
    ],
    ...
  }
]

https://webpack.js.org/configuration/module/#rule-exclude

7
On

What you're after might be the externals option in your webpack.config.js

module.exports = {
  //...
  externals: {
     './MyModuleFile': 'MyModule',
  }
};

This assumes you will include the script in your HTML manually which will expose the MyModule global

If you'd instead really like to use ES6 import, you could use the same technique because everything you put in there will just be exported as is

module.exports = {
  //...
  externals: {
     './MyModuleFile': 'import("MyModuleUrl")',
  }
};

But make sure you use the async version of import

import('./MyModuleFile').then(({default: MyModule}) => doSomethingWith(MyModule));

Or alternatively use the webpackIgnore comment to keep the import as is without changing the config

import(/* webpackIgnore: true */'MyModuleUrl').then(({default: MyModule}) => doSomethingWith(MyModule));