-
Notifications
You must be signed in to change notification settings - Fork 16
/
index.ts
219 lines (199 loc) · 5.93 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
import fs from 'node:fs'
import path from 'node:path'
import type { Plugin, ResolvedConfig } from 'vite'
import { parse as parseAst } from 'acorn'
import {
DEFAULT_EXTENSIONS,
KNOWN_SFC_EXTENSIONS,
KNOWN_ASSET_TYPES,
KNOWN_CSS_TYPES,
} from 'vite-plugin-utils/constant'
import { MagicString, cleanUrl } from 'vite-plugin-utils/function'
import { analyzer } from './analyze'
import { generateImport } from './generate-import'
import { generateExport } from './generate-export'
import { isCommonjs } from './utils'
import { DynaimcRequire } from './dynamic-require'
export const TAG = '[vite-plugin-commonjs]'
export interface Options {
filter?: (id: string) => boolean | undefined
dynamic?: {
/**
* 1. `true` - Match all possibilities as much as possible, more like `webpack`
* 2. `false` - It behaves more like `@rollup/plugin-dynamic-import-vars`
* @default true
*/
loose?: boolean
/**
* If you want to exclude some files
* e.g.
* ```js
* commonjs({
* dynamic: {
* onFiles: files => files.filter(f => f !== 'types.d.ts')
* }
* })
* ```
*/
onFiles?: (files: string[], id: string) => typeof files | undefined
}
}
export default function commonjs(options: Options = {}): Plugin {
let config: ResolvedConfig
let extensions = DEFAULT_EXTENSIONS
let dynaimcRequire: DynaimcRequire
return {
name: 'vite-plugin-commonjs',
configResolved(_config) {
config = _config
// https://github.com/vitejs/vite/blob/v4.3.0/packages/vite/src/node/config.ts#L498
if (config.resolve?.extensions) extensions = config.resolve.extensions
dynaimcRequire = new DynaimcRequire(_config, {
...options,
extensions: [
...extensions,
...KNOWN_SFC_EXTENSIONS,
...KNOWN_ASSET_TYPES.map(type => '.' + type),
...KNOWN_CSS_TYPES.map(type => '.' + type),
],
})
// esbuild plugin for Vite's Pre-Bundling
_config.optimizeDeps.esbuildOptions ??= {}
_config.optimizeDeps.esbuildOptions.plugins ??= []
_config.optimizeDeps.esbuildOptions.plugins.push({
name: 'vite-plugin-commonjs:pre-bundle',
setup(build) {
build.onLoad({ filter: /.*/ }, async ({ path: id }) => {
let code: string
try {
code = fs.readFileSync(id, 'utf8')
} catch (error) {
return
}
const contents = await transformCommonjs({
options,
code,
id,
extensions,
dynaimcRequire,
})
if (contents != null) {
return { contents }
}
})
},
})
},
transform(code, id) {
return transformCommonjs({
options,
code,
id,
extensions,
dynaimcRequire,
})
},
}
}
async function transformCommonjs({
options,
code,
id,
extensions,
dynaimcRequire,
}: {
options: Options,
code: string,
id: string,
extensions: string[],
dynaimcRequire: DynaimcRequire,
}) {
if (!(extensions.includes(path.extname(id)) || extensions.includes(path.extname(cleanUrl(id))))) return
if (!isCommonjs(code)) return
const userCondition = options.filter?.(id)
if (userCondition === false) return
// exclude `node_modules` by default
// here can only get the files in `node_modules/.vite` and `node_modules/vite/dist/client`, others will be handled by Pre-Bundling
if (userCondition !== true && id.includes('node_modules')) return
let ast: AcornNode
try {
ast = parseAst(code, { sourceType: 'module', ecmaVersion: 2020 }) as AcornNode
} catch (error) {
// ignore as it might not be a JS file, the subsequent plugins will catch the error
return null
}
const analyzed = analyzer(ast, code, id)
const imports = generateImport(analyzed)
const exportRuntime = id.includes('node_modules/.vite')
// Bypass Pre-build
? null
: generateExport(analyzed)
const dynamics = await dynaimcRequire.generateRuntime(analyzed)
const hoistImports = []
const ms = new MagicString(code)
// require
for (const impt of imports) {
const {
node,
importExpression,
importedName,
} = impt
if (importExpression && importedName) {
// TODO: Merge duplicated require id
hoistImports.push(importExpression + ';')
ms.overwrite(node.start, node.end, importedName)
}
}
if (hoistImports.length) {
ms.prepend([
`/* ${TAG} import-hoist-S */`,
...hoistImports,
`/* ${TAG} import-hoist-E */`,
].join(' '))
}
// exports
if (exportRuntime) {
const polyfill = [
`/* ${TAG} export-runtime-S */`,
exportRuntime.polyfill,
`/* ${TAG} export-runtime-E */`,
].join(' ')
const _exports = [
`/* ${TAG} export-statement-S */`,
exportRuntime.exportDeclaration,
`/* ${TAG} export-statement-E */`,
].filter(Boolean)
.join('\n')
ms.prepend(polyfill).append(_exports)
}
// dynamic require
if (dynamics) {
const requires: string[] = []
const runtimes: string[] = []
let count = 0
for (const dynamic of dynamics) {
const { node, normally, dynaimc: dymc } = dynamic
if (normally) {
const name = `__require2import__${count++}__`
requires.push(`import * as ${name} from "${normally}";`)
ms.overwrite(node.callee.start, node.callee.end, name)
} else if (dymc) {
requires.push(...dymc.importee.map(impt => impt + ';'))
runtimes.push(dymc.runtimeFn)
ms.overwrite(node.callee.start, node.callee.end, dymc.runtimeName)
}
}
if (requires.length) {
ms.prepend([
`/* ${TAG} import-require2import-S */`,
...requires,
`/* ${TAG} import-require2import-E */`,
].join(' '))
}
if (runtimes.length) {
ms.append(runtimes.join('\n'))
}
}
const str = ms.toString()
return str !== code ? str : null
}