Skip to content

Commit

Permalink
feat: allow options.preferBuiltins to be function
Browse files Browse the repository at this point in the history
  • Loading branch information
younggglcy committed Sep 23, 2024
1 parent 0af45c2 commit eacaf46
Showing 1 changed file with 11 additions and 6 deletions.
17 changes: 11 additions & 6 deletions packages/node-resolve/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ export function nodeResolve(opts = {}) {
const idToPackageInfo = new Map();
const mainFields = getMainFields(options);
const useBrowserOverrides = mainFields.indexOf('browser') !== -1;
const isPreferBuiltinsSet = options.preferBuiltins === true || options.preferBuiltins === false;
const isPreferBuiltinsSet = Object.prototype.hasOwnProperty.call(options, 'preferBuiltins');
const preferBuiltins = isPreferBuiltinsSet ? options.preferBuiltins : true;
const rootDir = resolve(options.rootDir || process.cwd());
let { dedupe } = options;
Expand Down Expand Up @@ -194,8 +194,10 @@ export function nodeResolve(opts = {}) {
});

const importeeIsBuiltin = builtinModules.includes(importee.replace(nodeImportPrefix, ''));
const preferImporteeIsBuiltin =
typeof preferBuiltins === 'function' ? preferBuiltins(importee) : preferBuiltins;
const resolved =
importeeIsBuiltin && preferBuiltins
importeeIsBuiltin && preferImporteeIsBuiltin
? {
packageInfo: undefined,
hasModuleSideEffects: () => null,
Expand Down Expand Up @@ -230,11 +232,14 @@ export function nodeResolve(opts = {}) {
idToPackageInfo.set(location, packageInfo);

if (hasPackageEntry) {
if (importeeIsBuiltin && preferBuiltins) {
if (importeeIsBuiltin && preferImporteeIsBuiltin) {
if (!isPreferBuiltinsSet && resolvedWithoutBuiltins && resolved !== importee) {
context.warn(
`preferring built-in module '${importee}' over local alternative at '${resolvedWithoutBuiltins.location}', pass 'preferBuiltins: false' to disable this behavior or 'preferBuiltins: true' to disable this warning`
);
context.warn({
message:
`preferring built-in module '${importee}' over local alternative at '${resolvedWithoutBuiltins.location}', pass 'preferBuiltins: false' to disable this behavior 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.`,
pluginCode: 'PREFER_BUILTINS'
});
}
return false;
} else if (jail && location.indexOf(normalize(jail.trim(sep))) !== 0) {
Expand Down

0 comments on commit eacaf46

Please # to comment.