From 7e12e8c040b4bec302f762967f1a4dda4431e626 Mon Sep 17 00:00:00 2001 From: younggglcy Date: Thu, 6 Jun 2024 19:27:47 +0800 Subject: [PATCH] test: add testcase about passing function to preferBuiltins --- .../prefer-builtin-local-and-builtin.js | 4 +++ packages/node-resolve/test/prefer-builtins.js | 36 +++++++++++++++---- 2 files changed, 34 insertions(+), 6 deletions(-) create mode 100644 packages/node-resolve/test/fixtures/prefer-builtin-local-and-builtin.js diff --git a/packages/node-resolve/test/fixtures/prefer-builtin-local-and-builtin.js b/packages/node-resolve/test/fixtures/prefer-builtin-local-and-builtin.js new file mode 100644 index 000000000..de1bf9637 --- /dev/null +++ b/packages/node-resolve/test/fixtures/prefer-builtin-local-and-builtin.js @@ -0,0 +1,4 @@ +import { sep } from 'path'; +import events from 'events'; + +export default { sep, events }; diff --git a/packages/node-resolve/test/prefer-builtins.js b/packages/node-resolve/test/prefer-builtins.js index 27d69d771..9f9998629 100644 --- a/packages/node-resolve/test/prefer-builtins.js +++ b/packages/node-resolve/test/prefer-builtins.js @@ -30,13 +30,12 @@ test('handles importing builtins', async (t) => { }); test('warning when preferring a builtin module, no explicit configuration', async (t) => { - let warning = null; + let warning = ''; await rollup({ input: 'prefer-builtin.js', - onwarn({ message }) { - // eslint-disable-next-line no-bitwise - if (~message.indexOf('preferring')) { - warning = message; + onwarn({ message, pluginCode }) { + if (pluginCode === 'PREFER_BUILTINS') { + warning += message; } }, plugins: [nodeResolve()] @@ -47,7 +46,8 @@ test('warning when preferring a builtin module, no explicit configuration', asyn warning, `preferring built-in module 'events' over local alternative ` + `at '${localPath}', pass 'preferBuiltins: false' to disable this behavior ` + - `or 'preferBuiltins: true' to disable this warning` + `or 'preferBuiltins: true' to disable this warning.` + + `or passing a function to 'preferBuiltins' to provide more fine-grained control over which built-in modules to prefer.` ); }); @@ -134,3 +134,27 @@ test('detects builtins imported with node: protocol', async (t) => { t.is(warnings.length, 0); }); + +test('accpet passing a function to determine which builtins to prefer', async (t) => { + const warnings = []; + const bundle = await rollup({ + input: 'prefer-builtin-local-and-builtin.js', + onwarn({ message }) { + warnings.push(message); + }, + plugins: [ + nodeResolve({ + preferBuiltins: (id) => id !== 'events' + }) + ] + }); + + const { + module: { exports } + } = await testBundle(t, bundle); + + t.is(warnings.length, 0); + t.is(exports.sep, require('node:path').sep); + t.not(exports.events, require('node:events')); + t.is(exports.events, 'not the built-in events module'); +});