/
esbuild.ts
100 lines (87 loc) · 2.84 KB
/
esbuild.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import { build } from '@umijs/bundler-utils/compiled/esbuild';
import { winPath } from '@umijs/utils';
import path from 'path';
import { IFatherBundlessConfig, IFatherPlatformTypes } from '../../../../types';
import type { IJSTransformer } from '../types';
/**
* create a replacer for transform alias path to relative path
*/
function createAliasReplacer(opts: { alias: IFatherBundlessConfig['alias'] }) {
const alias = opts.alias || {};
return function replacer(context: string, request: string) {
let absReq = '';
for (const rule in alias) {
// replace prefix
if (request.startsWith(`${rule}/`)) {
absReq = path.join(alias[rule], request.slice(rule.length + 1));
break;
}
// replace full path
if (request === rule) {
absReq = alias[rule];
break;
}
}
// transform to relative path
if (absReq) {
const rltReq = winPath(path.relative(context, absReq));
return rltReq.startsWith('..') ? rltReq : `./${rltReq}`;
}
return request;
};
}
/**
* esbuild transformer
*/
const esbuildTransformer: IJSTransformer = async function () {
const replacer = createAliasReplacer({ alias: this.config.alias });
let { outputFiles } = await build({
// do not emit file
write: false,
// enable bundle for trigger onResolve hook, but all deps will be externalized
bundle: true,
// write false will not write file to file system,but sourcemap need this to get sources
outdir: path.relative(
this.paths.cwd,
path.dirname(this.paths.itemDistAbsPath),
),
sourcemap: this.config.sourcemap && 'linked',
logLevel: 'silent',
format: this.config.format,
define: this.config.define,
platform: this.config.platform,
charset: 'utf8',
target:
this.config.platform === IFatherPlatformTypes.NODE ? 'node14' : 'es6',
// esbuild need relative entry path
entryPoints: [path.relative(this.paths.cwd, this.paths.fileAbsPath)],
absWorkingDir: this.paths.cwd,
plugins: [
{
name: 'plugin-father-alias',
setup: (builder) => {
builder.onResolve({ filter: /.*/ }, (args) => {
if (args.kind === 'entry-point') {
// skip entry point
return { path: path.join(args.resolveDir, args.path) };
} else if (args.path.startsWith('.')) {
// skip relative module
return { path: args.path, external: true };
}
// try to replace alias to relative path
return {
path: replacer(args.resolveDir, args.path),
external: true,
};
});
},
},
],
});
if (outputFiles.length === 2) {
const [map, result] = outputFiles;
return [result.text, map.text];
}
return [outputFiles[0].text];
};
export default esbuildTransformer;