diff --git a/README.md b/README.md index 1c9c161..d0d1c69 100644 --- a/README.md +++ b/README.md @@ -43,11 +43,25 @@ export default { {find:'somelibrary-1.0.0', replacement: './mylocallibrary-1.5.0'}, //remap a library with a specific version {find:/^i18n\!(.*)/, replacement: '$1.js'}, //remove something in front of the import and append an extension (e.g. loaders, for files that were previously transpiled via the AMD module, to properly handle them in rollup as internals now) //for whatever reason, replace all .js extensions with .wasm - {find:/^(.*)\.js$/, replacement: '$1.wasm'} + {find:/^(.*)\.js$/, replacement: '$1.wasm'} ] }) ], }; + +// or with object syntax +export default { + input: './src/index.js', + plugins: [ + alias({ + resolve: ['.jsx', '.js'], + entries: { + something: '../../../something', + 'somelibrary-1.0.0': './mylocallibrary-1.5.0', + } + }) + ], +}; ``` The order of the entries is important, in that the first rules are applied first. diff --git a/src/index.js b/src/index.js index f724c12..5a6a206 100644 --- a/src/index.js +++ b/src/index.js @@ -40,12 +40,24 @@ const normalizeId = (id) => { return id; }; +const getEntries = ({ entries }) => { + if (!entries) { + return []; + } + + if (Array.isArray(entries)) { + return entries; + } + + return Object.keys(entries).map(key => ({ find: key, replacement: entries[key] })); +}; + export default function alias(options = {}) { const resolve = Array.isArray(options.resolve) ? options.resolve : ['.js']; - const entries = options.entries?options.entries:[]; + const entries = getEntries(options); // No aliases? - if (!entries || entries.length === 0) { + if (entries.length === 0) { return { resolveId: noop, }; diff --git a/test/index.js b/test/index.js index 23be12a..c99cd1a 100644 --- a/test/index.js +++ b/test/index.js @@ -23,7 +23,7 @@ test('defaults', (t) => { t.is(typeof result.resolveId, 'function'); }); -test('Simple aliasing', (t) => { +test('Simple aliasing (array)', (t) => { const result = alias({ entries: [ {find:'foo', replacement:'bar'}, @@ -41,6 +41,24 @@ test('Simple aliasing', (t) => { t.is(resolved3, 'global'); }); +test('Simple aliasing (object)', (t) => { + const result = alias({ + entries: { + foo: 'bar', + pony: 'paradise', + './local': 'global' + } + }); + + const resolved = result.resolveId('foo', '/src/importer.js'); + const resolved2 = result.resolveId('pony', '/src/importer.js'); + const resolved3 = result.resolveId('./local', '/src/importer.js'); + + t.is(resolved, 'bar'); + t.is(resolved2, 'paradise'); + t.is(resolved3, 'global'); +}); + test('RegExp aliasing', (t) => { const result = alias({ entries: [