Combining aliasing and custom resolving algorithms in Rollup.js

Web Development

Vladislav Bogomaz

|

Oct 29, 2019

Combining aliasing and custom resolving algorithms in Rollup.js

Web Development

Vladislav Bogomaz

|

Oct 29, 2019

Combining aliasing and custom resolving algorithms in Rollup.js

Web Development

Vladislav Bogomaz

|

Oct 29, 2019

Or why I created rollup-plugin-module-replacement

Written for Medium.com

Have you ever needed to create an alias in Rollup project? Certainly.

Have you ever faced a problem with resolving made by popular plugins like rollup-plugin-alias? Most likely.

The problem

Most rollup plugins do their own resolve under the hood. If your project needs to use node-resolve algorithm(or any other) together with aliases it may become an issue.

Solution

$ yarn add -D rollup-plugin-module-replacement 
# OR
$ npm install --save-dev rollup-plugin-module-replacement

How to use it

Rollup-plugin-module-replacement has a nice Readme. Example:

// rollup.config.js
import replacement from "rollup-plugin-module-replacement";
import resolve from "rollup-plugin-node-resolve";
 
const customResolver = resolve({
  extensions: [".mjs", ".js", ".jsx", ".json", ".sass", ".scss"]
});
const projectRootDir = path.resolve(__dirname);
 
export default {
  // ...
  plugins: [
    replacement(
      {
        entries: [
          {
            find: "src",
            replacement: path.resolve(projectRootDir, "src")
            // OR place `customResolver` here. See explanation below.
          }
        ]
      },
      customResolver
    ),
    resolve()
  ]
};

In above example we made an alias src and still keep node-resolve algorithm for your files that are "aliased" with src by passing customResolver option. Also we keep resolve() plugin separately in plugins list for other files that are not aliased with src.

customResolver option can be passed inside each entree too for granular control over resolving.

customResolver also can be your own function, not plugin.

In same manner you can chain other plugins by using that architecture.

Bonus

Initially plugin was developed to basically mimic the Webpack NormalModuleReplacementPluginfunctionality in Rollup. You can use it like this too:

// rollup.config.js
import replacement from "rollup-plugin-module-replacement";
 
export default {
  // ...
  plugins: [
    replacement({
      entries: [
        {
          find: /(.*)-APP_TARGET(\.*)/,
          replacement: importee =>
            importee.replace(/-APP_TARGET/, `-${appTarget}`)
        }
      ]
    })
  ]
};

Conclusion

If you have any questions or issues, or found an error, please feel free to reach me on GitHub project page or on Twitter.