import path, { posix } from 'node:path'; import { fileURLToPath } from 'node:url'; import os from 'node:os'; import { describe, it, expect } from 'vitest'; import { rollup } from 'rollup'; import nodeResolvePlugin from '@rollup/plugin-node-resolve'; import alias from '~package'; const DIRNAME = fileURLToPath(new URL('.', import.meta.url)); const isWindows = os.platform() === 'win32'; /** * Helper function to test configuration with Rollup * @param plugins is an array of plugins for Rollup, they should include "alias" * @param externalIds is an array of ids that will be external * @param tests is an array of pairs [source, importer] */ function resolveWithRollup( plugins: any[], externalIds: string[], tests: { source: string; importer?: string; options?: any }[] ) { if (!plugins.find((p) => p.name === 'alias')) { throw new Error('`plugins` should include the alias plugin.'); } // Coordinate between the Rollup build lifecycle and our test assertions. let settle!: (value: (string | null)[]) => void; let settleErr!: (reason?: unknown) => void; const resultsPromise = new Promise<(string | null)[]>((res, rej) => { settle = res; settleErr = rej; }); return rollup({ input: 'dummy-input', plugins: [ { name: 'test-plugin', buildStart() { // Resolve the requested ids using Rollup's resolver in the proper context. Promise.all( tests.map(({ source, importer, options }) => // @ts-expect-error - this context is provided by Rollup this.resolve(source, importer, options).then((result: any) => result ? result.id : null ) ) ) .then(settle) .catch(settleErr); }, resolveId(id: string) { if (id === 'dummy-input') return id; if (externalIds.includes(id)) return { id, external: true } as any; return null; }, load(id: string) { if (id === 'dummy-input') return 'console.log("test");'; return null; } }, ...plugins ] }).then(async (bundle) => { try { const results = await resultsPromise; return results; } finally { await bundle.close(); } }); } /** * Helper function to test configuration with Rollup and injected alias plugin */ function resolveAliasWithRollup( aliasOptions: any, externalIds: string[], tests: { source: string; importer?: string; options?: any }[] ) { return resolveWithRollup([alias(aliasOptions)], externalIds, tests); } describe('plugin-alias', () => { it('type', () => { expect(typeof alias).toBe('function'); }); it('instance', () => { const result = alias(); expect(typeof result).toBe('object'); expect(typeof (result as any).resolveId).toBe('function'); }); it('defaults', () => { const result = alias({}); expect(typeof result).toBe('object'); expect(typeof (result as any).resolveId).toBe('function'); }); it('Simple aliasing (array)', async () => { const result = await resolveAliasWithRollup( { entries: [ { find: 'foo', replacement: 'bar' }, { find: 'pony', replacement: 'paradise' }, { find: './local', replacement: 'global' } ] }, ['bar', 'paradise', 'global'], [ { source: 'foo', importer: '/src/importer.js' }, { source: 'pony', importer: '/src/importer.js' }, { source: './local', importer: '/src/importer.js' } ] ); expect(result).toEqual(['bar', 'paradise', 'global']); }); it('Simple aliasing (object)', async () => { const result = await resolveAliasWithRollup( { entries: { foo: 'bar', pony: 'paradise', './local': 'global' } }, ['bar', 'paradise', 'global'], [ { source: 'foo', importer: '/src/importer.js' }, { source: 'pony', importer: '/src/importer.js' }, { source: './local', importer: '/src/importer.js' } ] ); expect(result).toEqual(['bar', 'paradise', 'global']); }); it('RegExp aliasing', async () => { const result = await resolveAliasWithRollup( { entries: [ { find: /f(o+)bar/, replacement: 'f$1bar2019' }, { find: new RegExp('.*pony.*'), replacement: 'i/am/a/barbie/girl' }, { find: /^test\/$/, replacement: 'this/is/strict' } ] }, ['fooooooooobar2019', 'i/am/a/barbie/girl', 'this/is/strict'], [ { source: 'fooooooooobar', importer: '/src/importer.js' }, { source: 'im/a/little/pony/yes', importer: '/src/importer.js' }, { source: './test', importer: '/src/importer.js' }, { source: 'test', importer: '/src/importer.js' }, { source: 'test/', importer: '/src/importer.js' } ] ); expect(result).toEqual([ 'fooooooooobar2019', 'i/am/a/barbie/girl', null, null, 'this/is/strict' ]); }); it('Replaces string aliases literally', async () => { const result = await resolveAliasWithRollup( { entries: [ { find: 'id', replacement: '$$' }, { find: 'at', replacement: '$&co' } ] }, ['$$', '$&co'], [ { source: 'id', importer: '/src/importer.js' }, { source: 'at', importer: '/src/importer.js' } ] ); expect(result).toEqual(['$$', '$&co']); }); it('Will not confuse modules with similar names', async () => { const result = await resolveAliasWithRollup( { entries: [ { find: 'foo', replacement: 'bar' }, { find: './foo', replacement: 'bar' } ] }, [], [ { source: 'foo2', importer: '/src/importer.js' }, { source: './fooze/bar', importer: '/src/importer.js' }, { source: './someFile.foo', importer: '/src/importer.js' } ] ); expect(result).toEqual([null, null, null]); }); it('Alias entry file', async () => { const result = await resolveAliasWithRollup( { entries: [{ find: 'abacaxi', replacement: './abacaxi' }] }, ['./abacaxi/entry.js'], [{ source: 'abacaxi/entry.js' }] ); expect(result).toEqual(['./abacaxi/entry.js']); }); it('i/am/a/file', async () => { const result = await resolveAliasWithRollup( { entries: [{ find: 'resolve', replacement: 'i/am/a/file' }] }, ['i/am/a/file'], [{ source: 'resolve', importer: '/src/import.js' }] ); expect(result).toEqual(['i/am/a/file']); }); it('Windows absolute path aliasing', async () => { if (!isWindows) { expect(1).toBe(1); return; } const result = await resolveAliasWithRollup( { entries: [{ find: 'resolve', replacement: 'E:\\react\\node_modules\\fbjs\\lib\\warning' }] }, [], [{ source: 'resolve', importer: posix.resolve(DIRNAME, './fixtures/index.js') }] ); expect(result).toEqual(['E:\\react\\node_modules\\fbjs\\lib\\warning']); }); const getModuleIdsFromBundle = (bundle: any) => { if (bundle.modules) { return Promise.resolve(bundle.modules.map((module: any) => module.id)); } return bundle .generate({ format: 'es' }) .then((generated: any) => { if (generated.output) { return generated.output.length ? generated.output : Object.keys(generated.output).map((chunkName) => generated.output[chunkName]); } return [generated]; }) .then((chunks: any[]) => chunks.reduce((moduleIds, chunk) => moduleIds.concat(Object.keys(chunk.modules)), []) ); }; it('Works in rollup with non fake input', async () => { const bundle = await rollup({ input: './test/fixtures/index.js', plugins: [ alias({ entries: [ { find: 'fancyNumber', replacement: './aliasMe' }, { find: './anotherFancyNumber', replacement: './localAliasMe' }, { find: 'numberFolder', replacement: './folder' }, { find: './numberFolder', replacement: './folder' } ] }) ] }); const moduleIds: string[] = await getModuleIdsFromBundle(bundle); const normalizedIds = moduleIds.map((id) => path.resolve(id)).sort(); expect(normalizedIds.length).toBe(5); [ '/fixtures/aliasMe.js', '/fixtures/folder/anotherNumber.js', '/fixtures/index.js', '/fixtures/localAliasMe.js', '/fixtures/nonAliased.js' ] .map((id) => path.normalize(id)) .forEach((expectedId, index) => { expect(normalizedIds[index].endsWith(expectedId)).toBe(true); }); }); // Global customResolver function is covered by the plugin-like variant below. it('Local customResolver function', async () => { const localCustomResult = 'localCustomResult'; const result = await resolveAliasWithRollup( { entries: [ { find: 'test', replacement: path.resolve('./test/files/folder/hipster.jsx'), customResolver: () => localCustomResult } ] }, [], [{ source: 'test', importer: posix.resolve(DIRNAME, './files/index.js') }] ); expect(result).toEqual([localCustomResult]); }); it('Global customResolver plugin-like object', async () => { const customResult = 'customResult'; const result = await resolveAliasWithRollup( { entries: [{ find: 'test', replacement: path.resolve('./test/files/folder/hipster.jsx') }], customResolver: { resolveId: () => customResult } }, [], [{ source: 'test', importer: posix.resolve(DIRNAME, './files/index.js') }] ); expect(result).toEqual([customResult]); }); it('Local customResolver plugin-like object', async () => { const localCustomResult = 'localCustomResult'; const result = await resolveAliasWithRollup( { entries: [ { find: 'test', replacement: path.resolve('./test/files/folder/hipster.jsx'), customResolver: { resolveId: () => localCustomResult } } ] }, [], [{ source: 'test', importer: posix.resolve(DIRNAME, './files/index.js') }] ); expect(result).toEqual([localCustomResult]); }); it('supports node-resolve as a custom resolver', async () => { const result = await resolveAliasWithRollup( { entries: [ { find: 'local-resolver', replacement: path.resolve(DIRNAME, 'fixtures'), customResolver: nodeResolvePlugin() }, { find: 'global-resolver', replacement: path.resolve(DIRNAME, 'fixtures', 'folder') } ], customResolver: nodeResolvePlugin() }, [], [ { source: 'local-resolver', importer: posix.resolve(DIRNAME, './files/index.js') }, { source: 'global-resolver', importer: posix.resolve(DIRNAME, './files/index.js') } ] ); expect(result).toEqual([ path.resolve(DIRNAME, 'fixtures', 'index.js'), path.resolve(DIRNAME, 'fixtures', 'folder', 'index.js') ]); }); it('Alias + rollup-plugin-node-resolve', async () => { const bundle = await rollup({ input: './test/fixtures/index.js', plugins: [ alias({ entries: [ { find: 'fancyNumber', replacement: './aliasMe' }, { find: './anotherFancyNumber', replacement: './localAliasMe' }, { find: 'numberFolder/anotherNumber', replacement: './folder' }, { find: './numberFolder', replacement: './folder' }, { find: 'superdeep', replacement: './deep/deep2' } ] }), nodeResolvePlugin() ] }); const moduleIds: string[] = await getModuleIdsFromBundle(bundle); const normalizedIds = moduleIds.map((id) => path.resolve(id)).sort(); expect(normalizedIds.length).toBe(6); [ '/fixtures/aliasMe.js', '/fixtures/folder/anotherNumber.js', '/fixtures/folder/deep/deep2/index.js', '/fixtures/index.js', '/fixtures/localAliasMe.js', '/fixtures/nonAliased.js' ] .map((id) => path.normalize(id)) .forEach((expectedId, index) => { expect(normalizedIds[index].endsWith(expectedId)).toBe(true); }); }); it('Forwards isEntry and custom options to a custom resolver', async () => { const resolverCalls: any[] = []; const result = await resolveAliasWithRollup( { entries: { entry: 'entry-point', nonEntry: 'non-entry-point' }, customResolver: (...args: any[]) => { resolverCalls.push(args); return args[0]; } }, [], [ { source: 'entry', importer: '/src/importer.js', options: { isEntry: true } }, { source: 'nonEntry', importer: '/src/importer.js', options: { attributes: {}, isEntry: false, custom: { test: 42 } } } ] ); expect(resolverCalls).toEqual([ ['entry-point', '/src/importer.js', { attributes: {}, custom: void 0, isEntry: true }], [ 'non-entry-point', '/src/importer.js', { attributes: {}, custom: { test: 42 }, isEntry: false } ] ]); expect(result).toEqual(['entry-point', 'non-entry-point']); }); it('Forwards isEntry and custom options to other plugins', async () => { const resolverCalls: any[] = []; const result = await resolveWithRollup( [ alias({ entries: { entry: 'entry-point', nonEntry: 'non-entry-point' } }), { name: 'test', resolveId(...args: any[]) { resolverCalls.push(args); if (['entry-point', 'non-entry-point'].includes(args[0])) { return { id: args[0], external: true } as any; } return null; } } ], [], [ { source: 'entry', importer: '/src/importer.js', options: { isEntry: true } }, { source: 'nonEntry', importer: '/src/importer.js', options: { isEntry: false, custom: { test: 42 } } } ] ); expect(resolverCalls).toEqual([ ['entry-point', '/src/importer.js', { attributes: {}, custom: void 0, isEntry: true }], [ 'non-entry-point', '/src/importer.js', { attributes: {}, custom: { test: 42 }, isEntry: false } ] ]); expect(result).toEqual(['entry-point', 'non-entry-point']); }); it('CustomResolver plugin-like object with buildStart', async () => { const count = { entry: 0, option: 0 }; await resolveAliasWithRollup( { entries: [ { find: 'this', replacement: path.resolve('./that.jsx'), customResolver: { resolveId: () => 'custom Resolver', buildStart: () => (count.entry += 1) } }, { find: 'that', replacement: '' } ], customResolver: { buildStart: () => (count.option += 1) } }, [], [] ); expect(count).toEqual({ entry: 1, option: 1 }); }); it('show warning for non-absolute non-plugin resolved id', async () => { const warnList: any[] = []; await rollup({ input: './test/fixtures/warn.js', plugins: [ alias({ entries: [ { find: '@', replacement: path.relative(process.cwd(), path.join(DIRNAME, './fixtures/folder')) } ] }) ], onwarn(log) { const formattedLog = { ...log, message: (log as any).message.replace(/\\/g, '/') } as any; warnList.push(formattedLog); } }); expect(warnList).toMatchObject([ { message: '[plugin alias] rewrote @/warn-importee.js to test/fixtures/folder/warn-importee.js but was not an absolute path and was not handled by other plugins. ' + 'This will lead to duplicated modules for the same path. ' + 'To avoid duplicating modules, you should resolve to an absolute path.', code: 'PLUGIN_WARNING', plugin: 'alias' } ]); }); });