forked from vitejs/vite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrollup.config.ts
320 lines (297 loc) · 8.48 KB
/
rollup.config.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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
import { readFileSync } from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import nodeResolve from '@rollup/plugin-node-resolve'
import commonjs from '@rollup/plugin-commonjs'
import json from '@rollup/plugin-json'
import MagicString from 'magic-string'
import type { Plugin } from 'rollup'
import { defineConfig } from 'rollup'
import esbuild, { type Options as esbuildOptions } from 'rollup-plugin-esbuild'
import licensePlugin from './rollupLicensePlugin'
const pkg = JSON.parse(
readFileSync(new URL('./package.json', import.meta.url)).toString(),
)
const __dirname = fileURLToPath(new URL('.', import.meta.url))
const envConfig = defineConfig({
input: path.resolve(__dirname, 'src/client/env.ts'),
plugins: [
esbuild({
tsconfig: path.resolve(__dirname, 'src/client/tsconfig.json'),
}),
],
output: {
file: path.resolve(__dirname, 'dist/client', 'env.mjs'),
},
})
const clientConfig = defineConfig({
input: path.resolve(__dirname, 'src/client/client.ts'),
external: ['@vite/env'],
plugins: [
esbuild({
tsconfig: path.resolve(__dirname, 'src/client/tsconfig.json'),
}),
],
output: {
file: path.resolve(__dirname, 'dist/client', 'client.mjs'),
},
})
const sharedNodeOptions = defineConfig({
treeshake: {
moduleSideEffects: 'no-external',
propertyReadSideEffects: false,
tryCatchDeoptimization: false,
},
output: {
dir: './dist',
entryFileNames: `node/[name].js`,
chunkFileNames: 'node/chunks/dep-[hash].js',
exports: 'named',
format: 'esm',
externalLiveBindings: false,
freeze: false,
},
onwarn(warning, warn) {
if (warning.message.includes('Circular dependency')) {
return
}
warn(warning)
},
})
function createSharedNodePlugins({
esbuildOptions,
}: {
esbuildOptions?: esbuildOptions
}): Plugin[] {
return [
nodeResolve({ preferBuiltins: true }),
esbuild({
tsconfig: path.resolve(__dirname, 'src/node/tsconfig.json'),
target: 'node18',
...esbuildOptions,
}),
commonjs({
extensions: ['.js'],
// Optional peer deps of ws. Native deps that are mostly for performance.
// Since ws is not that perf critical for us, just ignore these deps.
ignore: ['bufferutil', 'utf-8-validate'],
sourceMap: false,
}),
json(),
]
}
const nodeConfig = defineConfig({
...sharedNodeOptions,
input: {
index: path.resolve(__dirname, 'src/node/index.ts'),
cli: path.resolve(__dirname, 'src/node/cli.ts'),
constants: path.resolve(__dirname, 'src/node/constants.ts'),
},
external: [
/^vite\//,
'fsevents',
'lightningcss',
'rollup/parseAst',
...Object.keys(pkg.dependencies),
],
plugins: [
// Some deps have try...catch require of optional deps, but rollup will
// generate code that force require them upfront for side effects.
// Shim them with eval() so rollup can skip these calls.
shimDepsPlugin({
// chokidar -> fsevents
'fsevents-handler.js': {
src: `require('fsevents')`,
replacement: `__require('fsevents')`,
},
// postcss-import -> sugarss
'process-content.js': {
src: 'require("sugarss")',
replacement: `__require('sugarss')`,
},
'lilconfig/src/index.js': {
pattern: /: require;/g,
replacement: `: __require;`,
},
// postcss-load-config calls require after register ts-node
'postcss-load-config/src/index.js': {
pattern: /require(?=\((configFile|'ts-node')\))/g,
replacement: `__require`,
},
// postcss-import uses the `resolve` dep if the `resolve` option is not passed.
// However, we always pass the `resolve` option. Remove this import to avoid
// bundling the `resolve` dep.
'postcss-import/index.js': {
src: 'const resolveId = require("./lib/resolve-id")',
replacement: 'const resolveId = (id) => id',
},
'postcss-import/lib/parse-styles.js': {
src: 'const resolveId = require("./resolve-id")',
replacement: 'const resolveId = (id) => id',
},
}),
...createSharedNodePlugins({}),
licensePlugin(
path.resolve(__dirname, 'LICENSE.md'),
'Vite core license',
'Vite',
),
cjsPatchPlugin(),
],
})
const moduleRunnerConfig = defineConfig({
...sharedNodeOptions,
input: {
'module-runner': path.resolve(__dirname, 'src/module-runner/index.ts'),
},
external: [
'fsevents',
'lightningcss',
'rollup/parseAst',
...Object.keys(pkg.dependencies),
],
plugins: [
...createSharedNodePlugins({ esbuildOptions: { minifySyntax: true } }),
bundleSizeLimit(50),
],
})
const cjsConfig = defineConfig({
...sharedNodeOptions,
input: {
publicUtils: path.resolve(__dirname, 'src/node/publicUtils.ts'),
},
output: {
dir: './dist',
entryFileNames: `node-cjs/[name].cjs`,
chunkFileNames: 'node-cjs/chunks/dep-[hash].js',
exports: 'named',
format: 'cjs',
externalLiveBindings: false,
freeze: false,
sourcemap: false,
},
external: ['fsevents', ...Object.keys(pkg.dependencies)],
plugins: [...createSharedNodePlugins({}), bundleSizeLimit(175)],
})
export default defineConfig([
envConfig,
clientConfig,
nodeConfig,
moduleRunnerConfig,
cjsConfig,
])
// #region Plugins
interface ShimOptions {
src?: string
replacement: string
pattern?: RegExp
}
function shimDepsPlugin(deps: Record<string, ShimOptions>): Plugin {
const transformed: Record<string, boolean> = {}
return {
name: 'shim-deps',
transform(code, id) {
for (const file in deps) {
if (id.replace(/\\/g, '/').endsWith(file)) {
const { src, replacement, pattern } = deps[file]
const magicString = new MagicString(code)
if (src) {
const pos = code.indexOf(src)
if (pos < 0) {
this.error(
`Could not find expected src "${src}" in file "${file}"`,
)
}
transformed[file] = true
magicString.overwrite(pos, pos + src.length, replacement)
console.log(`shimmed: ${file}`)
}
if (pattern) {
let match
while ((match = pattern.exec(code))) {
transformed[file] = true
const start = match.index
const end = start + match[0].length
magicString.overwrite(start, end, replacement)
}
if (!transformed[file]) {
this.error(
`Could not find expected pattern "${pattern}" in file "${file}"`,
)
}
console.log(`shimmed: ${file}`)
}
return magicString.toString()
}
}
},
buildEnd(err) {
if (!err) {
for (const file in deps) {
if (!transformed[file]) {
this.error(
`Did not find "${file}" which is supposed to be shimmed, was the file renamed?`,
)
}
}
}
},
}
}
/**
* Inject CJS Context for each deps chunk
*/
function cjsPatchPlugin(): Plugin {
const cjsPatch = `
import { fileURLToPath as __cjs_fileURLToPath } from 'node:url';
import { dirname as __cjs_dirname } from 'node:path';
import { createRequire as __cjs_createRequire } from 'node:module';
const __filename = __cjs_fileURLToPath(import.meta.url);
const __dirname = __cjs_dirname(__filename);
const require = __cjs_createRequire(import.meta.url);
const __require = require;
`.trimStart()
return {
name: 'cjs-chunk-patch',
renderChunk(code, chunk) {
if (!chunk.fileName.includes('chunks/dep-')) return
const match = /^(?:import[\s\S]*?;\s*)+/.exec(code)
const index = match ? match.index! + match[0].length : 0
const s = new MagicString(code)
// inject after the last `import`
s.appendRight(index, cjsPatch)
console.log('patched cjs context: ' + chunk.fileName)
return s.toString()
},
}
}
/**
* Guard the bundle size
*
* @param limit size in kB
*/
function bundleSizeLimit(limit: number): Plugin {
let size = 0
return {
name: 'bundle-limit',
generateBundle(_, bundle) {
size = Buffer.byteLength(
Object.values(bundle)
.map((i) => ('code' in i ? i.code : ''))
.join(''),
'utf-8',
)
},
closeBundle() {
const kb = size / 1000
if (kb > limit) {
this.error(
`Bundle size exceeded ${limit} kB, current size is ${kb.toFixed(
2,
)}kb.`,
)
}
},
}
}
// #endregion