-
Notifications
You must be signed in to change notification settings - Fork 27
/
build.ts
292 lines (258 loc) · 10.3 KB
/
build.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
import { existsSync, promises as fsp } from 'node:fs'
import { pathToFileURL } from 'node:url'
import { basename, dirname, join, normalize, resolve } from 'pathe'
import { filename } from 'pathe/utils'
import { readPackageJSON } from 'pkg-types'
import { parse } from 'tsconfck'
import type { TSConfig } from 'pkg-types'
import { defu } from 'defu'
import { createJiti } from 'jiti'
import { anyOf, createRegExp } from 'magic-regexp'
import { consola } from 'consola'
import type { NuxtModule } from '@nuxt/schema'
import { findExports, resolvePath } from 'mlly'
import type { ESMExport } from 'mlly'
import { defineCommand } from 'citty'
import { convertCompilerOptionsFromJson } from 'typescript'
import { name, version } from '../../package.json'
export default defineCommand({
meta: {
name: 'build',
description: 'Build module for distribution',
},
args: {
cwd: {
type: 'string',
description: 'Current working directory',
},
rootDir: {
type: 'positional',
description: 'Root directory',
required: false,
},
outDir: {
type: 'string',
},
sourcemap: {
type: 'boolean',
},
stub: {
type: 'boolean',
},
},
async run(context) {
const { build } = await import('unbuild')
const cwd = resolve(context.args.cwd || context.args.rootDir || '.')
const jiti = createJiti(cwd)
const outDir = context.args.outDir || 'dist'
await build(cwd, false, {
declaration: 'node16',
sourcemap: context.args.sourcemap,
stub: context.args.stub,
outDir,
entries: [
'src/module',
{
input: 'src/runtime/',
outDir: `${outDir}/runtime`,
addRelativeDeclarationExtensions: true,
ext: 'js',
pattern: [
'**',
'!**/*.stories.{js,cts,mts,ts,jsx,tsx}', // ignore storybook files
'!**/*.{spec,test}.{js,cts,mts,ts,jsx,tsx}', // ignore tests
],
esbuild: {
jsxImportSource: 'vue',
jsx: 'automatic',
jsxFactory: 'h',
},
},
],
rollup: {
esbuild: {
target: 'esnext',
},
emitCJS: false,
cjsBridge: false,
},
externals: [
/dist[\\/]runtime[\\/]/,
'@nuxt/schema',
'@nuxt/schema-nightly',
'@nuxt/schema-edge',
'@nuxt/kit',
'@nuxt/kit-nightly',
'@nuxt/kit-edge',
'#app',
'#app/nuxt',
'nuxt',
'nuxt-nightly',
'nuxt-edge',
'nuxt3',
'vue',
'vue-demi',
],
hooks: {
async 'mkdist:entry:options'(_ctx, entry, options) {
options.typescript = defu(options.typescript, {
compilerOptions: await loadTSCompilerOptions(entry.input),
})
},
async 'rollup:options'(ctx, options) {
const [entry] = ctx.buildEntries
const mergedCompilerOptions = defu({
noEmit: false,
paths: {
'#app/nuxt': ['./node_modules/nuxt/dist/app/nuxt'],
},
}, ctx.options.rollup.dts.compilerOptions, await loadTSCompilerOptions(entry!.path))
ctx.options.rollup.dts.compilerOptions = convertCompilerOptionsFromJson(mergedCompilerOptions, entry!.path).options
options.plugins ||= []
if (!Array.isArray(options.plugins))
options.plugins = [options.plugins]
const runtimeEntries = ctx.options.entries.filter(entry => entry.builder === 'mkdist')
const runtimeDirs = runtimeEntries.map(entry => basename(entry.input))
const RUNTIME_RE = createRegExp(anyOf(...runtimeDirs).and(anyOf('/', '\\')))
// Add extension for imports of runtime files in build
options.plugins.unshift({
name: 'nuxt-module-builder:runtime-externals',
async resolveId(id, importer) {
if (!RUNTIME_RE.test(id))
return
const resolved = await this.resolve(id, importer, { skipSelf: true })
if (!resolved)
return
const normalizedId = normalize(resolved.id)
for (const entry of runtimeEntries) {
if (!normalizedId.includes(entry.input))
continue
const distFile = await resolvePath(join(dirname(pathToFileURL(normalizedId).href.replace(entry.input, entry.outDir!)), filename(normalizedId)))
if (distFile) {
return {
external: true,
id: distFile,
}
}
}
},
})
},
async 'rollup:done'(ctx) {
// Load module meta
const moduleEntryPath = resolve(ctx.options.outDir, 'module.mjs')
const moduleFn = await jiti.import<NuxtModule<Record<string, unknown>>>(pathToFileURL(moduleEntryPath).toString(), { default: true }).catch((err) => {
consola.error(err)
consola.error('Cannot load module. Please check dist:', moduleEntryPath)
return null
})
if (!moduleFn) {
return
}
const moduleMeta = await moduleFn.getMeta?.() || {}
// Enhance meta using package.json
if (ctx.pkg) {
if (!moduleMeta.name) {
moduleMeta.name = ctx.pkg.name
}
if (!moduleMeta.version) {
moduleMeta.version = ctx.pkg.version
}
}
// Add module builder metadata
moduleMeta.builder = {
[name]: version,
unbuild: await readPackageJSON('unbuild').then(r => r.version).catch(() => 'unknown'),
}
// Write meta
const metaFile = resolve(ctx.options.outDir, 'module.json')
await fsp.writeFile(metaFile, JSON.stringify(moduleMeta, null, 2), 'utf8')
// Generate types
await writeTypes(ctx.options.outDir, ctx.options.stub)
},
async 'build:done'(ctx) {
const logs = [...ctx.warnings].filter(l => l.startsWith('Potential missing package.json files:'))
if (logs.filter(l => l.match(/\.d\.ts/)).length > 0) {
consola.warn(`\`@nuxt/module-builder\` no longer supports Node10 TypeScript module resolution and will no longer generate \`.d.ts\` declaration files. You can update these paths to use the \`.d.mts\` extension instead.`)
}
if (logs.filter(l => l.match(/module\.cjs/)).length > 0) {
consola.warn(`\`@nuxt/module-builder\` will no longer generate \`module.cjs\` as this is not required for Nuxt v3+. You can safely remove replace this with \`module.mjs\` in your \`package.json\`.`)
}
const pkg = await readPackageJSON(cwd)
if (pkg?.types && !existsSync(resolve(cwd, pkg.types))) {
consola.warn(`Please remove the \`types\` field from package.json as it is no longer required for Bundler TypeScript module resolution.`)
}
},
},
})
},
})
async function writeTypes(distDir: string, isStub: boolean) {
const dtsFile = resolve(distDir, 'types.d.mts')
if (existsSync(dtsFile)) {
return
}
const moduleReExports: ESMExport[] = []
if (!isStub) {
// Read generated module types
const moduleTypesFile = resolve(distDir, 'module.d.mts')
const moduleTypes = await fsp.readFile(moduleTypesFile, 'utf8').catch(() => '')
const normalisedModuleTypes = moduleTypes
// Replace `export { type Foo }` with `export { Foo }`
.replace(/export\s*\{.*?\}/gs, match => match.replace(/\b(type|interface)\b/g, ''))
for (const e of findExports(normalisedModuleTypes)) {
moduleReExports.push(e)
}
}
const appShims: string[] = []
const schemaShims: string[] = []
const moduleImports: string[] = []
const schemaImports: string[] = []
const moduleExports: string[] = []
const hasTypeExport = (name: string) => isStub || moduleReExports.find(exp => exp.names?.includes(name))
if (!hasTypeExport('ModuleOptions')) {
schemaImports.push('NuxtModule')
moduleImports.push('default as Module')
moduleExports.push(`export type ModuleOptions = typeof Module extends NuxtModule<infer O> ? Partial<O> : Record<string, any>`)
}
if (hasTypeExport('ModuleHooks')) {
moduleImports.push('ModuleHooks')
schemaShims.push(' interface NuxtHooks extends ModuleHooks {}')
}
if (hasTypeExport('ModuleRuntimeHooks')) {
moduleImports.push('ModuleRuntimeHooks')
appShims.push(` interface RuntimeNuxtHooks extends ModuleRuntimeHooks {}`)
}
if (hasTypeExport('ModuleRuntimeConfig')) {
moduleImports.push('ModuleRuntimeConfig')
schemaShims.push(' interface RuntimeConfig extends ModuleRuntimeConfig {}')
}
if (hasTypeExport('ModulePublicRuntimeConfig')) {
moduleImports.push('ModulePublicRuntimeConfig')
schemaShims.push(' interface PublicRuntimeConfig extends ModulePublicRuntimeConfig {}')
}
const dtsContents = `
${schemaImports.length ? `import type { ${schemaImports.join(', ')} } from '@nuxt/schema'` : ''}
${moduleImports.length ? `import type { ${moduleImports.join(', ')} } from './module.mjs'` : ''}
${appShims.length ? `declare module '#app' {\n${appShims.join('\n')}\n}\n` : ''}
${schemaShims.length ? `declare module '@nuxt/schema' {\n${schemaShims.join('\n')}\n}\n` : ''}
${moduleExports.length ? `\n${moduleExports.join('\n')}` : ''}
${isStub ? 'export * from "./module.mjs"' : ''}
${moduleReExports[0] ? `\nexport { ${moduleReExports[0].names.map(n => (n === 'default' ? '' : 'type ') + n).join(', ')} } from './module.mjs'` : ''}
`.trim().replace(/[\n\r]{3,}/g, '\n\n') + '\n'
await fsp.writeFile(dtsFile, dtsContents, 'utf8')
}
async function loadTSCompilerOptions(path: string): Promise<NonNullable<TSConfig['compilerOptions']>> {
const config = await parse(path)
const resolvedCompilerOptions = config?.tsconfig.compilerOptions || {}
// TODO: this should probably be ported to tsconfck?
for (const { tsconfig, tsconfigFile } of config.extended || []) {
for (const alias in tsconfig.compilerOptions?.paths || {}) {
resolvedCompilerOptions.paths[alias] = resolvedCompilerOptions.paths[alias].map((p: string) => {
if (!/^\.{1,2}(?:\/|$)/.test(p)) return p
return resolve(dirname(tsconfigFile), p)
})
}
}
return resolvedCompilerOptions
}