/
index.ts
304 lines (287 loc) · 8.66 KB
/
index.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
import fs from 'fs'
import path from 'path'
import { transform as transformToEs5 } from 'buble'
import {
build as esbuild,
BuildResult,
formatMessages,
Plugin as EsbuildPlugin,
} from 'esbuild'
import { NormalizedOptions, Format } from '..'
import { getDeps, loadPkg } from '../load'
import { Logger } from '../log'
import { nodeProtocolPlugin } from './node-protocol'
import { externalPlugin } from './external'
import { postcssPlugin } from './postcss'
import { sveltePlugin } from './svelte'
import consola from 'consola'
import { getBabel, truthy } from '../utils'
import { PrettyError } from '../errors'
import { transform } from 'sucrase'
import { swcPlugin } from './swc'
import { nativeNodeModulesPlugin } from './native-node-module'
const getOutputExtensionMap = (
pkgTypeField: string | undefined,
format: Format
) => {
const isModule = pkgTypeField === 'module'
const map: any = {}
if (isModule && format === 'cjs') {
map['.js'] = '.cjs'
}
if (!isModule && format === 'esm') {
map['.js'] = '.mjs'
}
if (format === 'iife') {
map['.js'] = '.global.js'
}
return map
}
export async function runEsbuild(
options: NormalizedOptions,
{
format,
css,
logger,
buildDependencies,
}: {
format: Format
css?: Map<string, string>
buildDependencies: Set<string>
logger: Logger
}
) {
const pkg = await loadPkg(process.cwd())
const deps = await getDeps(process.cwd())
const external = [
// Exclude dependencies, e.g. `lodash`, `lodash/get`
...deps.map((dep) => new RegExp(`^${dep}($|\\/|\\\\)`)),
...(options.external || []),
]
const outDir = options.outDir
const outExtension = getOutputExtensionMap(pkg.type, format)
const env: { [k: string]: string } = {
...options.env,
}
if (options.replaceNodeEnv) {
env.NODE_ENV =
options.minify || options.minifyWhitespace ? 'production' : 'development'
}
logger.info(format, 'Build start')
const startTime = Date.now()
let result: BuildResult | undefined
const splitting =
format === 'iife'
? false
: typeof options.splitting === 'boolean'
? options.splitting
: format === 'esm'
const platform = options.platform || 'node'
const loader = options.loader || {}
const esbuildPlugins: Array<EsbuildPlugin | false | undefined> = [
format === 'cjs' && nodeProtocolPlugin(),
{
name: 'modify-options',
setup(build) {
if (options.esbuildOptions) {
options.esbuildOptions(build.initialOptions, { format })
}
},
},
// esbuild's `external` option doesn't support RegExp
// So here we use a custom plugin to implement it
format !== 'iife' &&
externalPlugin({
external,
skipNodeModulesBundle: options.skipNodeModulesBundle,
tsconfigResolvePaths: options.tsconfigResolvePaths,
}),
options.tsconfigDecoratorMetadata && swcPlugin(),
nativeNodeModulesPlugin(),
postcssPlugin({ css }),
sveltePlugin({ css }),
...(options.esbuildPlugins || []),
]
try {
result = await esbuild({
entryPoints: options.entryPoints,
format: format === 'cjs' && splitting ? 'esm' : format,
bundle: typeof options.bundle === 'undefined' ? true : options.bundle,
platform,
globalName: options.globalName,
jsxFactory: options.jsxFactory,
jsxFragment: options.jsxFragment,
sourcemap: options.sourcemap,
target: options.target === 'es5' ? 'es2016' : options.target,
footer: options.footer,
banner: options.banner,
tsconfig: options.tsconfig,
loader: {
'.aac': 'file',
'.css': 'file',
'.eot': 'file',
'.flac': 'file',
'.gif': 'file',
'.jpeg': 'file',
'.jpg': 'file',
'.mp3': 'file',
'.mp4': 'file',
'.ogg': 'file',
'.otf': 'file',
'.png': 'file',
'.svg': 'file',
'.ttf': 'file',
'.wav': 'file',
'.webm': 'file',
'.webp': 'file',
'.woff': 'file',
'.woff2': 'file',
...loader,
},
mainFields:
platform === 'node'
? ['module', 'main']
: ['browser', 'module', 'main'],
plugins: esbuildPlugins.filter(truthy),
define: {
...(format === 'cjs'
? {
'import.meta.url': 'importMetaUrlShim',
}
: {}),
...options.define,
...Object.keys(env).reduce((res, key) => {
const value = JSON.stringify(env[key])
return {
...res,
[`process.env.${key}`]: value,
[`import.meta.env.${key}`]: value,
}
}, {}),
},
inject: [
format === 'cjs' ? path.join(__dirname, '../assets/cjs_shims.js') : '',
format === 'esm' ? path.join(__dirname, '../assets/esm_shims.js') : '',
...(options.inject || []),
].filter(Boolean),
outdir:
options.legacyOutput && format !== 'cjs'
? path.join(outDir, format)
: outDir,
outExtension: options.legacyOutput ? undefined : outExtension,
write: false,
splitting,
logLevel: 'error',
minify: options.minify,
minifyWhitespace: options.minifyWhitespace,
minifyIdentifiers: options.minifyIdentifiers,
minifySyntax: options.minifySyntax,
keepNames: options.keepNames,
incremental: !!options.watch,
pure: typeof options.pure === 'string' ? [options.pure] : options.pure,
metafile: true,
})
} catch (error) {
logger.error(format, 'Build failed')
throw error
}
if (result && result.warnings) {
const messages = result.warnings.filter((warning) => {
if (
warning.text.includes(
`This call to "require" will not be bundled because`
) ||
warning.text.includes(`Indirect calls to "require" will not be bundled`)
)
return false
return true
})
const formatted = await formatMessages(messages, {
kind: 'warning',
color: true,
})
formatted.forEach((message) => {
consola.warn(message)
})
}
// Manually write files
if (result && result.outputFiles) {
const timeInMs = Date.now() - startTime
logger.success(format, `Build success in ${Math.floor(timeInMs)}ms`)
await Promise.all(
result.outputFiles.map(async (file) => {
const dir = path.dirname(file.path)
const outPath = file.path
const ext = path.extname(outPath)
const comeFromSource = ext === '.js' || ext === outExtension['.js']
await fs.promises.mkdir(dir, { recursive: true })
let contents = file.text
let mode: number | undefined
if (contents[0] === '#' && contents[1] === '!') {
mode = 0o755
}
if (comeFromSource) {
if (options.babel) {
const babel = getBabel()
if (babel) {
contents = await babel
.transformAsync(contents, {
filename: file.path,
})
.then((res) => res?.code || contents)
} else {
throw new PrettyError(
`@babel/core is not found in ${process.cwd()}`
)
}
}
if (options.target === 'es5') {
try {
contents = transformToEs5(contents, {
source: file.path,
file: file.path,
transforms: {
modules: false,
arrow: true,
dangerousTaggedTemplateString: true,
spreadRest: true,
},
}).code
} catch (error: any) {
throw new PrettyError(
`Error compiling to es5 target:\n${error.snippet}`
)
}
}
// Workaround to enable code splitting for cjs format
// Manually transform esm to cjs
// TODO: remove this once esbuild supports code splitting for cjs natively
if (splitting && format === 'cjs') {
contents = transform(contents, {
filePath: file.path,
transforms: ['imports'],
}).code
}
}
await fs.promises.writeFile(outPath, contents, {
encoding: 'utf8',
mode,
})
})
)
}
if (result.metafile) {
for (const file of Object.keys(result.metafile.inputs)) {
buildDependencies.add(file)
}
if (options.metafile) {
const outPath = path.resolve(outDir, `metafile-${format}.json`)
await fs.promises.mkdir(path.dirname(outPath), { recursive: true })
await fs.promises.writeFile(
outPath,
JSON.stringify(result.metafile),
'utf8'
)
}
}
}