'How to substitute sources for browser bundle with Rollup?

Using rollup is it possible to replace a specific source by another source in a NPM package during a browser bundle? Note this source is dynamically imported via import('./relativeFile.js') (I want this to be replaced).

I've specified { "browser": { "./relativeFile.js": "./browserFile.js" } } in package.json of one of the node_modules to see how it goes, but Rollup still bundles ./relativeFile.js instead. I appreciate any help.



Solution 1:[1]

Use the nodeResolve and replace plugins to indicate it is a browser bundle. Rollup will then replace Node sources by Web Browser sources.

import { nodeResolve } from '@rollup/plugin-node-resolve';
import replace from '@rollup/plugin-replace';

export default {
  plugins: [
    nodeResolve({
      browser: true,
    }),
    replace({
      values:{
        'process.browser': true,
      },
    }),
  ],
};

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Klaider