Skip to content

Commit

Permalink
fix(module-tools): load empty object instead throw error when js reso…
Browse files Browse the repository at this point in the history
…lve result is false (#4796)
  • Loading branch information
10Derozan authored Oct 17, 2023
1 parent 29feb81 commit 194c9a5
Show file tree
Hide file tree
Showing 12 changed files with 114 additions and 25 deletions.
6 changes: 6 additions & 0 deletions .changeset/big-chefs-wait.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@modern-js/module-tools': patch
---

fix(module-tools): load empty object instead throw error when js resolve result is false
fix(module-tools): 当 js resolve 结果为 false 时,加载空对象替代抛出错误
20 changes: 17 additions & 3 deletions packages/solutions/module-tools/src/builder/esbuild/adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -186,11 +186,19 @@ export const adapterPlugin = (compiler: ICompiler): Plugin => {
const isExternal = getIsExternal(originalFilePath);
const dir =
args.resolveDir ?? (args.importer ? dirname(args.importer) : root);
const resultPath = isExternal
? args.path
: getResultPath(originalFilePath, dir, args.kind);
if (resultPath === false) {
debugResolve('empty resolve:', args);
return {
path: '/empty-stub',
sideEffects: false,
};
}
const sideEffects = await getSideEffects(originalFilePath, isExternal);
const result = {
path: isExternal
? args.path
: getResultPath(originalFilePath, dir, args.kind),
path: resultPath,
external: isExternal,
namespace: isExternal ? undefined : 'file',
sideEffects,
Expand Down Expand Up @@ -218,6 +226,12 @@ export const adapterPlugin = (compiler: ICompiler): Plugin => {
return;
}

if (args.path === '/empty-stub') {
return {
contents: 'module.exports = {}',
};
}

compiler.addWatchFile(args.path);
let result = await compiler.hooks.load.promise(args);
if (!result) {
Expand Down
8 changes: 4 additions & 4 deletions packages/solutions/module-tools/src/builder/esbuild/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import { adapterPlugin } from './adapter';
import { TransformContext } from './transform';
import { SourcemapContext } from './sourcemap';
import { createRenderChunkHook, createTransformHook } from './hook';
import { createResolver } from './resolve';
import { createJsResolver, createCssResolver } from './resolve';
import { initWatcher } from './watch';

export class EsbuildCompiler implements ICompiler {
Expand Down Expand Up @@ -57,7 +57,7 @@ export class EsbuildCompiler implements ICompiler {

css_resolve: (id: string, dir: string) => string;

node_resolve: (id: string, dir: string, kind: ImportKind) => string;
node_resolve: (id: string, dir: string, kind: ImportKind) => string | false;

watcher?: FSWatcher;

Expand Down Expand Up @@ -89,13 +89,13 @@ export class EsbuildCompiler implements ICompiler {
tsconfig: config.tsconfig,
mainFields: config.resolve.mainFields,
};
this.css_resolve = createResolver({
this.css_resolve = createCssResolver({
...resolveOptions,
resolveType: 'css',
extensions: cssExtensions,
preferRelative: true,
});
this.node_resolve = createResolver({
this.node_resolve = createJsResolver({
...resolveOptions,
resolveType: 'js',
extensions: config.resolve.jsExtensions,
Expand Down
43 changes: 30 additions & 13 deletions packages/solutions/module-tools/src/builder/esbuild/resolve.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,29 +56,46 @@ function createEnhancedResolve(options: ResolverOptions): {
};
}

export const createResolver = (options: ResolverOptions) => {
export const createJsResolver = (options: ResolverOptions) => {
const resolveCache = new Map<string, string>();
const { resolveSync, esmResolveSync } = createEnhancedResolve(options);
const resolver = (id: string, dir: string, kind?: ImportKind) => {
const cacheKey = id + dir + (kind || '');
const cacheResult = resolveCache.get(cacheKey);

if (cacheResult) {
return cacheResult;
}

let result: string | false;
if (options.resolveType === 'js') {
if (kind === 'import-statement' || kind === 'dynamic-import') {
result = esmResolveSync(dir, id);
} else {
result = resolveSync(dir, id);
}
if (kind === 'import-statement' || kind === 'dynamic-import') {
result = esmResolveSync(dir, id);
} else {
try {
result = resolveSync(dir, id);
} catch (err) {
result = resolveSync(dir, id.replace(/^~/, ''));
}
result = resolveSync(dir, id);
}

if (result) {
resolveCache.set(cacheKey, result);
}
return result;
};
return resolver;
};

export const createCssResolver = (options: ResolverOptions) => {
const resolveCache = new Map<string, string>();
const { resolveSync } = createEnhancedResolve(options);
const resolver = (id: string, dir: string, kind?: ImportKind) => {
const cacheKey = id + dir + (kind || '');
const cacheResult = resolveCache.get(cacheKey);
if (cacheResult) {
return cacheResult;
}

let result: string | false;
try {
result = resolveSync(dir, id);
} catch (err) {
result = resolveSync(dir, id.replace(/^~/, ''));
}
if (!result) {
throw new Error(`can not resolve ${id} from ${dir}`);
Expand Down
2 changes: 1 addition & 1 deletion packages/solutions/module-tools/src/types/esbuild.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ export type Context = {
export interface ICompiler {
reBuild: (type: 'link' | 'change', config: BaseBuildConfig) => Promise<void>;
css_resolve: (id: string, dir: string) => string;
node_resolve: (id: string, dir: string, kind: ImportKind) => string;
node_resolve: (id: string, dir: string, kind: ImportKind) => string | false;
init: () => Promise<void>;

watcher?: FSWatcher;
Expand Down
14 changes: 12 additions & 2 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
import { defineConfig } from '@modern-js/module-tools/defineConfig';

export default defineConfig({});
export default defineConfig({
buildConfig: {
input: ['./index.ts'],
},
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { runCli, initBeforeTest } from '../../../utils';

initBeforeTest();

describe('resolve', () => {
const fixtureDir = __dirname;
it('false', async () => {
const { success } = await runCli({
argv: ['build'],
appDirectory: fixtureDir,
});
expect(success).toBeTruthy();
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// In some directory structure, we can not resolve './util.inspect' from 'index.js' in 'object-inspect',
// For example, in bytedance internal monorepo solution, but here we can resolve it.

import xxx from 'object-inspect';

console.log('xxx:', xxx);
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { defineConfig } from '@modern-js/module-tools/defineConfig';

export default defineConfig({
buildConfig: {
input: ['./index.ts'],
},
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"name": "resolve-false",
"version": "1.0.0",
"devDependencies": {
"object-inspect": "1.13.0"
}
}
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
import { defineConfig } from '@modern-js/module-tools/defineConfig';

export default defineConfig({});
export default defineConfig({
buildConfig: {
input: ['./index.ts'],
},
});

0 comments on commit 194c9a5

Please sign in to comment.