Conditional requires/imports using Webpack

Viewed 208

A project I'm working on has a legacy JS codebase that didn't have any modules with import/export statements and that just defined new types directly on the window object. The resulting bundles just concatenated the source code together in the correct order.

Recently, this legacy code was modularized, but to make sure that the resulting bundles work exactly the same as they did before, all imports to legacy code are stripped from the source code using a webpack loader. So to webpack, there are no imports just like before.

Now, I'm trying to also start improving the bundles themselves and I'd like Webpack to stop ignoring these imports in specific Webpack entrypoints so that it actually resolves and imports all dependencies.

What this means is:

  1. If webpack is building the legacy bundles, all imports with paths starting with '@legacy' are ignored and during runtime the imported types are just resolved from the window object.
  2. If webpack is building one of the new entry points, all imports with paths starting with '@legacy' are processed and imported.

If it were just the 1st part, it would be easy. Currently I just have a loader that matches legacy imports with Regex and removes them from the source code. But now, because Webpack needs to follow these imports depending on the entry point, I can't strip the imports from the source code anymore.

I know I'll need to write a Webpack Plugin for this, but I haven't written one before so some pointers on how to achieve what I'm trying to do would be very helpful.

Example:

a.js - Module that imports "b.js"

b.js - Module that imports "c.js"

c.js - Module that doesn't import anything

If webpack is building code for one of the legacy bundles, once it encounters a.js trying to import b.js, it ignores the import.

If webpack is building code for one of the new bundles, once it encounters a.js trying to import b.js, it does so and also does the same for any imports b.js has.

Note that I'm trying to achieve this with a single webpack build/config.

Note: If it makes anything easier, the new kinds of bundles and the old kinds of bundles aren't going to be used together in the same page.

0 Answers
Related