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

2

7

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?

Lovesome answered 25/9, 2018 at 21:59 Comment(1)
Check out Webpack docs about conditions: as @connexo suggests, you need to exclude the part you don't want Webpack to resolve in the Webpack configuration file.Kriskrischer
H
10

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));
Hexyl answered 7/6, 2019 at 22:39 Comment(7)
This doesn't work for me. The webpack step works, but I get a "Error: Cannot find module" from webpackMissingModule, so its obviously still tying to use webpack, not the ES6 module loading from the browser directly. Is there a step I'm missing?Oospore
What's your externals config and how do you import your file?Hexyl
You can see all the details in this separate thread: #61050794Oospore
But I setup like this: externals: { '/ffmpeg/ffmpeg-webm.js': 'ffmpeg', },Oospore
And import like this : import ffmpeg from '/ffmpeg/ffmpeg-webm.js';Oospore
I've verified '/ffmpeg/ffmpeg-webm.js' is a valid addressOospore
You forgot to include the script in your html, adding it to externals does not include it for you. Eg: add <script src="/ffmpeg/ffmpeg-webm.js"></script> in the head of your appHexyl
I
-4

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

Ilianailine answered 25/9, 2018 at 22:8 Comment(1)
I thought that exclude will only exclude those files from being transformed, but they are still bundled. I tried it out, and I see that my file is still included into the bundle, which is what I am trying to avoid.Lovesome

© 2022 - 2024 — McMap. All rights reserved.