A Rollup plugin which allows to replace files in external dependency with local files.
- Initialize plugin
// rollup.config.js
export default {
plugins: [
mirrorReplacementPlugin({
packages: ['@foo/bar'], // ./node_modules/@foo/bar
}),
]
}
- Create file with same route as in mirrored package
- Now you file is used instead of original
- Export everything from mirrored file then write your extensions/overrides after, ecma specs allows to override.
// ./src/baz.js
export * from '@foo/bar/baz';
export const someValue = 'My custom value which will be used instead of original';
// vite.config.js
import { defineConfig, mergeConfig } from 'vite';
import { vueComponentNormalizer, vueHotReload } from 'vite-plugin-vue2';
import mirrorReplacementPlugin from './build/plugins/mirrorReplacement.mjs';
export default ({ command }) => {
const isBuild = command === 'build';
return defineConfig({
plugins: [
mirrorReplacementPlugin({
logLevel: isBuild ? 'info' : 'silent',
packages: ['@foo/bar'], // ./node_modules/@foo/bar
exclude: [vueComponentNormalizer, vueHotReload], // https://github.com/underfin/vite-plugin-vue2/blob/940ec45a3fd68bd9ba1b1a8808d96e6cbce13207/src/index.ts#L16
extensions: ['js', 'vue', 'mjs'],
}),
]
});
}
Name | Type | Default | Description |
---|---|---|---|
packages (required) | string[] |
undefined |
Names of mirrored packages |
rootDir | string |
process.cwd() |
Project root dir |
srcDir | string |
'./src' |
Project source dir relative to rootDir |
extensions | string[] |
['js', 'mjs'] |
File extensions affected by plugin |
include | `string | RegExp | string |
exclude | `string | RegExp | string |
logLevel | string |
'silent' |
Logs about replacements if not 'silent'
|
- Mirrored package must not be bundled in runtime
- Overridden variable can be used only in imports, but locally it won't be overridden.
Example:
// ./node_modules/@foo/bar/baz.js
export const name = 'John';
export function logName() {
console.log(name);
}
// ./node_modules/@foo/bar/lib.js
import { name } from './baz';
export function sayHi() {
console.log('Hello, ', name);
}
// ./src/baz.js (used instead of ./node_modules/@foo/bar/baz.js)
export * from '@foo/bar/baz';
export const name = 'Bob';
// ./src/index.js
import { sayHi } from '@foo/bar/lib';
import { logName } from './baz';
sayHi() // 'Bob' (export is overridden)
logName() // 'John' (local variable can't be overridden)
The only way 'fix' it is to copy/paste needed part in your mirror file:
// ./src/baz.js (used instead of ./node_modules/@foo/bar/baz.js)
export * from '@foo/bar/baz';
export const name = 'Bob';
export function logName() {
console.log(name);
}
// ./src/index.js
import { sayHi } from '@foo/bar/lib';
import { logName } from './baz';
sayHi() // 'Bob' (export is overridden)
logName() // 'Bob' (now also overridden)