What's the recommended way to import libraries inside webpack.config.js?

Viewed 146

I always used require call inside webpack.config.js to import libraries for my build workflow. However, recently I worked on a project where import is used.

Generally, it works fine but seems like some supporting tools that import webpack.config.js cannot import it when import is used inside of it with error:

Cannot use import statement outside a module.

As a tryout, I changed the config to run through babel and it worked, though for me looks like I am fine to use just good old require and official documentation still uses it.

Should I rollback import to avoid the caveats or I can use them without problem if I pass it through babel and renaming to webpack.config.babel.js?

1 Answers

After some research, I got to a solution - transpile webpack config before passing it to a library I used which failed to load it (eslint-import-resolver-webpack).

So, I don't load webpack.config.js directly, but via babel transpiler:

const webpackConfigTranspiled = babel.transformFileSync(
  path.resolve(__dirname, './webpack.config.js'),
).code;

Then pass the transpiled content to the library/tool:

settings: {
    'import/resolver': {
      webpack: webpackConfigTranspiled,
    },
    'css-modules': {
      basePath: 'src',
    },
  }
Related