jiek 1.1.13 → 2.0.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -1,8 +1,18 @@
1
1
  import { program } from 'commander'
2
2
  import pkg from 'jiek/package.json'
3
3
 
4
+ import { filterDescription } from '#~/commands/descriptions.ts'
5
+ import { IS_WORKSPACE } from '#~/commands/meta.ts'
6
+ import { type } from '#~/utils/filterSupport.ts'
7
+
4
8
  program
9
+ .name('jk/jiek')
5
10
  .version(pkg.version)
6
- .description(pkg.description)
7
- .option('--root <root>', 'root path')
8
- .option('-c, --config-path <configPath>', 'config path')
11
+ .description(`${pkg.description} - Version ${pkg.version}`)
12
+ .option('--root <root>', 'The root path of the project')
13
+ .option('-c, --config-path <configPath>', 'Custom jiek config path')
14
+
15
+ if (type !== '' && IS_WORKSPACE) {
16
+ program
17
+ .option('-f, --filter <filter>', filterDescription)
18
+ }
@@ -6,12 +6,16 @@ import { MultiBar, Presets } from 'cli-progress'
6
6
  import { program } from 'commander'
7
7
  import { execaCommand } from 'execa'
8
8
 
9
+ import { entriesDescription, filterDescription, outdirDescription } from '#~/commands/descriptions.ts'
10
+ import { IS_WORKSPACE } from '#~/commands/meta.ts'
11
+ import type { ProjectsGraph } from '#~/utils/filterSupport.ts'
12
+ import { filterPackagesGraph, getSelectedProjectsGraph } from '#~/utils/filterSupport.ts'
13
+ import { getWD } from '#~/utils/getWD.ts'
14
+ import { loadConfig } from '#~/utils/loadConfig.ts'
15
+ import { tsRegisterName } from '#~/utils/tsRegister.ts'
16
+
9
17
  import type { RollupProgressEvent, TemplateOptions } from '../rollup/base'
10
- import type { ProjectsGraph } from '../utils/filterSupport'
11
- import { filterPackagesGraph, getSelectedProjectsGraph } from '../utils/filterSupport'
12
- import { loadConfig } from '../utils/loadConfig'
13
- import { tsRegisterName } from '../utils/tsRegister'
14
- import { outdirDescription } from './descriptions'
18
+ import { BUILDER_TYPE_PACKAGE_NAME_MAP, BUILDER_TYPES } from '../rollup/base'
15
19
 
16
20
  declare module 'jiek' {
17
21
  export interface Config {
@@ -32,13 +36,21 @@ module.exports = require('jiek/rollup').template(${JSON.stringify(manifest, null
32
36
 
33
37
  const require = createRequire(import.meta.url)
34
38
 
39
+ const isDefault = process.env.JIEK_IS_ONLY_BUILD === 'true'
40
+
35
41
  const description = `
36
- Build the package according to the 'exports' field in the package.json.
37
- If you want to rewrite the rollup command options, you can pass the options after '--'.
38
- e.g. \`jiek build -- --watch\`
42
+ Build the package according to the 'exports' field from the package.json.
43
+ If you want to rewrite the \`rollup\` command options, you can pass the options after '--'.
44
+ ${isDefault ? 'This command is the default command.' : ''}
39
45
  `.trim()
40
46
 
41
- interface BuildOptions extends Record<string, unknown> {
47
+ interface BuildOptions {
48
+ /**
49
+ * Auto-detect the builder from the installed dependencies.
50
+ * If the builder is not installed, it will prompt the user to install it.
51
+ * If exists multiple builders, it will fall back to the 'esbuild'.
52
+ */
53
+ type?: typeof BUILDER_TYPES[number]
42
54
  /**
43
55
  * The output directory of the build, which relative to the target subpackage root directory.
44
56
  * Support with variables: 'PKG_NAME',
@@ -47,10 +59,11 @@ interface BuildOptions extends Record<string, unknown> {
47
59
  * @default 'dist'
48
60
  */
49
61
  outdir: string
62
+ watch: boolean
50
63
  silent: boolean
64
+ verbose: boolean
51
65
  entries?: string
52
66
  external?: string
53
- verbose: boolean
54
67
  noJs: boolean
55
68
  noDts: boolean
56
69
  noMin: boolean
@@ -59,6 +72,53 @@ interface BuildOptions extends Record<string, unknown> {
59
72
  */
60
73
  noClean: boolean
61
74
  onlyMin: boolean
75
+ /**
76
+ * The type of minify, support 'terser' and 'builder'.
77
+ *
78
+ * @default 'builder'
79
+ */
80
+ minType?: string
81
+ /**
82
+ * The path of the tsconfig file which is used to generate js and dts files.
83
+ * If not specified, it will be loaded from:
84
+ * - ./tsconfig.json
85
+ * - ./tsconfig.dts.json
86
+ * - ./tsconfig.build.json
87
+ */
88
+ tsconfig?: string
89
+ /**
90
+ * The path of the tsconfig file which is used to generate dts files.
91
+ * If not specified, it will be loaded from:
92
+ * - ./tsconfig.json
93
+ * - ./tsconfig.dts.json
94
+ */
95
+ dtsconfig?: string
96
+ }
97
+
98
+ async function checkDependency(dependency: string) {
99
+ try {
100
+ require.resolve(dependency)
101
+ } catch (e) {
102
+ console.error(`The package '${dependency}' is not installed, please install it first.`)
103
+ const answer = prompt('Do you want to install it now? (Y/n)', 'Y')
104
+ const { notWorkspace } = getWD()
105
+ if (answer === 'Y') {
106
+ await execaCommand(`pnpm install -${notWorkspace ? '' : 'w'}D ${dependency}`)
107
+ } else {
108
+ return
109
+ }
110
+ }
111
+ }
112
+
113
+ let DEFAULT_BUILDER_TYPE: typeof BUILDER_TYPES[number]
114
+ Object.entries(BUILDER_TYPE_PACKAGE_NAME_MAP).forEach(([type, packageName]) => {
115
+ try {
116
+ require.resolve(packageName)
117
+ DEFAULT_BUILDER_TYPE = type as typeof BUILDER_TYPES[number]
118
+ } catch { /* empty */ }
119
+ })
120
+ if (!DEFAULT_BUILDER_TYPE!) {
121
+ DEFAULT_BUILDER_TYPE = 'esbuild'
62
122
  }
63
123
 
64
124
  function parseBoolean(v?: unknown) {
@@ -66,43 +126,109 @@ function parseBoolean(v?: unknown) {
66
126
  return Boolean(v)
67
127
  }
68
128
 
69
- program
70
- .command('build')
129
+ const buildFilterDescription = `
130
+ ${filterDescription}
131
+ If you pass the --filter option, it will merge into the filters of the command.
132
+ `.trim()
133
+
134
+ const buildEntriesDescription = `
135
+ ${entriesDescription}
136
+ If you pass the --entries option, it will merge into the entries of the command.
137
+ `.trim()
138
+
139
+ const command = isDefault
140
+ ? program
141
+ .name('jb/jiek-build')
142
+ .helpCommand(false)
143
+ : program
144
+
145
+ if (IS_WORKSPACE) {
146
+ if (isDefault) {
147
+ command.argument('[filters]', buildFilterDescription)
148
+ } else {
149
+ command.command('build [filters]')
150
+ }
151
+ } else {
152
+ if (isDefault) {
153
+ command.argument('[entries]', buildEntriesDescription)
154
+ } else {
155
+ command.command('build [entries]')
156
+ }
157
+ }
158
+
159
+ command
71
160
  .description(description)
161
+ .option('-t, --type <TYPE>', `The type of build, support ${BUILDER_TYPES.map(s => `"${s}"`).join(', ')}.`, v => {
162
+ if (!BUILDER_TYPES.includes(v as any)) {
163
+ throw new Error(`The value of 'type' must be ${BUILDER_TYPES.map(s => `"${s}"`).join(', ')}`)
164
+ }
165
+ return String(v)
166
+ }, 'esbuild')
72
167
  .option('-o, --outdir <OUTDIR>', outdirDescription, String, 'dist')
73
- .option(
74
- '-e, --entries <ENTRIES>',
75
- "Specify the build entry-points of the package.json's 'exports' field.(support glob)"
76
- )
168
+ .option('-e, --entries <ENTRIES>', entriesDescription)
77
169
  .option('--external <EXTERNAL>', 'Specify the external dependencies of the package.', String)
78
170
  .option('-nj, --noJs', 'Do not output js files.', parseBoolean)
79
171
  .option('-nd, --noDts', 'Do not output dts files.', parseBoolean)
80
172
  .option('-nm, --noMin', 'Do not output minify files.', parseBoolean)
173
+ .option(
174
+ '--minType <MINTYPE>',
175
+ 'The type of minify, support "builder" and "terser".',
176
+ v => {
177
+ if (!['builder', 'terser'].includes(v)) {
178
+ throw new Error('The value of `minType` must be "builder" or "terser"')
179
+ }
180
+ return String(v)
181
+ }
182
+ )
81
183
  .option('-nc, --noClean', 'Do not clean the output directory before building.', parseBoolean)
82
184
  .option(
83
185
  '-om, --onlyMin',
84
186
  'Only output minify files, but dts files will still be output, it only replaces the js files.',
85
187
  parseBoolean
86
188
  )
189
+ .option('--tsconfig <TSCONFIG>', 'The path of the tsconfig file which is used to generate js and dts files.', String)
190
+ .option('--dtsconfig <DTSCONFIG>', 'The path of the tsconfig file which is used to generate dts files.', String)
191
+ .option('-w, --watch', 'Watch the file changes.', parseBoolean)
87
192
  .option('-s, --silent', "Don't display logs.", parseBoolean)
88
193
  .option('-v, --verbose', 'Display debug logs.', parseBoolean)
89
- .action(async ({
90
- outdir,
91
- silent,
92
- entries,
93
- external,
94
- verbose,
95
- noJs: withoutJs,
96
- noDts: withoutDts,
97
- noMin: withoutMin,
98
- noClean,
99
- onlyMin: onlyMin
100
- }: BuildOptions) => {
194
+ .action(async (commandFiltersOrEntries: string | undefined, options: BuildOptions) => {
195
+ /* eslint-disable prefer-const */
196
+ let {
197
+ type,
198
+ outdir,
199
+ watch,
200
+ silent,
201
+ verbose,
202
+ entries: optionEntries,
203
+ external,
204
+ noJs: withoutJs,
205
+ noDts: withoutDts,
206
+ noMin: withoutMin,
207
+ minType: minifyType,
208
+ noClean,
209
+ onlyMin,
210
+ tsconfig,
211
+ dtsconfig
212
+ } = options
213
+ /* eslint-enable prefer-const */
214
+ const resolvedType = type ?? DEFAULT_BUILDER_TYPE
215
+ if (!withoutJs) {
216
+ await checkDependency(BUILDER_TYPE_PACKAGE_NAME_MAP[resolvedType]!)
217
+ if (minifyType === 'builder') {
218
+ minifyType = resolvedType
219
+ }
220
+ }
221
+ if (!withoutMin) {
222
+ await checkDependency(
223
+ {
224
+ ...BUILDER_TYPE_PACKAGE_NAME_MAP,
225
+ terser: '@rollup/plugin-terser'
226
+ }[resolvedType]!
227
+ )
228
+ }
101
229
  let shouldPassThrough = false
102
230
 
103
- const passThroughOptions = program
104
- .parseOptions(process.argv)
105
- .unknown
231
+ const passThroughOptions = process.argv
106
232
  .reduce(
107
233
  (acc, value) => {
108
234
  if (shouldPassThrough) {
@@ -125,8 +251,16 @@ program
125
251
  throw new Error('Cannot use --without-js and --only-minify at the same time')
126
252
  }
127
253
 
254
+ let entries: string | undefined = [
255
+ optionEntries,
256
+ IS_WORKSPACE ? undefined : commandFiltersOrEntries
257
+ ].filter(Boolean).join(',')
258
+ if (entries.length === 0) {
259
+ entries = undefined
260
+ }
128
261
  const env = {
129
262
  ...process.env,
263
+ JIEK_BUILDER: type,
130
264
  JIEK_OUT_DIR: outdir,
131
265
  JIEK_CLEAN: String(!noClean),
132
266
  JIEK_ENTRIES: entries,
@@ -134,7 +268,10 @@ program
134
268
  JIEK_WITHOUT_JS: String(withoutJs),
135
269
  JIEK_WITHOUT_DTS: String(withoutDts),
136
270
  JIEK_WITHOUT_MINIFY: String(withoutMin),
137
- JIEK_ONLY_MINIFY: String(onlyMin)
271
+ JIEK_ONLY_MINIFY: String(onlyMin),
272
+ JIEK_MINIFY_TYPE: minifyType,
273
+ JIEK_TSCONFIG: tsconfig,
274
+ JIEK_DTSCONFIG: dtsconfig
138
275
  }
139
276
 
140
277
  const multiBars = new MultiBar({
@@ -174,12 +311,15 @@ program
174
311
  `${escapeManifestName ?? `anonymous-${i++}`}.rollup.config.js`
175
312
  )
176
313
  fs.writeFileSync(configFile, FILE_TEMPLATE(manifest))
177
- let prefix = ''
314
+ const command = [rollupBinaryPath, '--silent', '-c', configFile]
178
315
  if (tsRegisterName) {
179
- prefix = `node -r ${tsRegisterName} `
316
+ command.unshift(`node -r ${tsRegisterName}`)
180
317
  }
181
- const command = [`${prefix}${rollupBinaryPath} --silent -c ${configFile}`, ...passThroughOptions].join(' ')
182
- const child = execaCommand(command, {
318
+ if (watch) {
319
+ command.push('--watch')
320
+ }
321
+ command.push(...passThroughOptions)
322
+ const child = execaCommand(command.join(' '), {
183
323
  ipc: true,
184
324
  cwd: dir,
185
325
  env: {
@@ -207,7 +347,11 @@ program
207
347
  conditions
208
348
  }))
209
349
  )
210
- console.log(`Package '${manifest.name}' has ${targetsLength} targets to build`)
350
+ let initMessage = `Package '${manifest.name}' has ${targetsLength} targets to build`
351
+ if (watch) {
352
+ initMessage += ' and watching...'
353
+ }
354
+ console.log(initMessage)
211
355
  leafs.forEach(({ input }) => {
212
356
  inputMaxLen = Math.max(inputMaxLen, input.length)
213
357
  })
@@ -290,9 +434,23 @@ program
290
434
  })
291
435
  )
292
436
  }
293
- const filters = (program.getOptionValue('filter') as string | undefined)?.split(',')
437
+ const commandFilters = IS_WORKSPACE ? commandFiltersOrEntries : undefined
438
+ const filters = [
439
+ ...new Set([
440
+ ...(program.getOptionValue('filter') as string | undefined)
441
+ ?.split(',')
442
+ .map(s => s.trim())
443
+ .filter(s => s.length > 0)
444
+ ?? [],
445
+ ...commandFilters
446
+ ?.split(',')
447
+ .map(s => s.trim())
448
+ .filter(s => s.length > 0)
449
+ ?? []
450
+ ])
451
+ ]
294
452
  try {
295
- if (filters) {
453
+ if (filters.length > 0) {
296
454
  const packages = await filterPackagesGraph(filters)
297
455
  await Promise.all(packages.map(buildPackage))
298
456
  } else {
@@ -1,3 +1,15 @@
1
+ export const entriesDescription = `
2
+ Specify the build entry-points of the package.json's 'exports' field.
3
+ Support glob pattern and array.
4
+ .e.g. '.', './*', './sub/*', './a,./b'.
5
+ `.trim()
6
+
7
+ export const filterDescription = `
8
+ Filter the packages from the workspace.
9
+ Support fuzzy match and array.
10
+ .e.g. 'core,utils'.
11
+ `.trim()
12
+
1
13
  export const outdirDescription = `
2
14
  The output directory of the build, which relative to the target subpackage root directory.
3
15
  Support with variables: 'PKG_NAME',
@@ -0,0 +1,5 @@
1
+ import { getWD } from '#~/utils/getWD.ts'
2
+
3
+ const { notWorkspace } = getWD()
4
+
5
+ export const IS_WORKSPACE = !notWorkspace
@@ -17,6 +17,13 @@ export interface ConfigGenerateContext {
17
17
 
18
18
  export type OutputControl = boolean | ((context: ConfigGenerateContext) => boolean)
19
19
 
20
+ export const BUILDER_TYPES = ['esbuild', 'swc'] as const
21
+
22
+ export const BUILDER_TYPE_PACKAGE_NAME_MAP = {
23
+ esbuild: 'rollup-plugin-esbuild',
24
+ swc: 'rollup-plugin-swc3'
25
+ }
26
+
20
27
  export interface TemplateOptions {
21
28
  /**
22
29
  * When the user configures type: module, the generated output from entry points that don't
@@ -27,6 +34,21 @@ export interface TemplateOptions {
27
34
  * @default true
28
35
  */
29
36
  crossModuleConvertor?: boolean
37
+ /**
38
+ * Auto-detect the builder from the installed dependencies.
39
+ * If the builder is not installed, it will prompt the user to install it.
40
+ * If exists multiple builders, it will fall back to the 'esbuild'.
41
+ *
42
+ * @default 'esbuild'
43
+ */
44
+ builder?:
45
+ | typeof BUILDER_TYPES[number]
46
+ | ({
47
+ type: 'esbuild'
48
+ } & import('rollup-plugin-esbuild').Options)
49
+ | ({
50
+ type: 'swc'
51
+ } & import('rollup-plugin-swc3').PluginOptions)
30
52
  output?: {
31
53
  /**
32
54
  * @default true
@@ -35,6 +57,24 @@ export interface TemplateOptions {
35
57
  * When minify is set to 'only-minify', the output will direct output minified files.
36
58
  */
37
59
  minify?: boolean | 'only-minify'
60
+ minifyOptions?:
61
+ | typeof BUILDER_TYPES[number]
62
+ | 'terser'
63
+ | (
64
+ {
65
+ type: 'terser'
66
+ } & import('@rollup/plugin-terser').Options
67
+ )
68
+ | (
69
+ {
70
+ type: 'esbuild'
71
+ } & Parameters<typeof import('rollup-plugin-esbuild').minify>[0]
72
+ )
73
+ | (
74
+ {
75
+ type: 'swc'
76
+ } & Parameters<typeof import('rollup-plugin-swc3').minify>[0]
77
+ )
38
78
  /**
39
79
  * @default 'dist'
40
80
  */
@@ -8,11 +8,9 @@ import { getWorkspaceDir } from '@jiek/utils/getWorkspaceDir'
8
8
  import commonjs from '@rollup/plugin-commonjs'
9
9
  import json from '@rollup/plugin-json'
10
10
  import { nodeResolve } from '@rollup/plugin-node-resolve'
11
- import terser from '@rollup/plugin-terser'
12
11
  import { sendMessage } from 'execa'
13
12
  import { isMatch } from 'micromatch'
14
13
  import type { InputPluginOption, OutputOptions, OutputPlugin, Plugin, RollupOptions } from 'rollup'
15
- import esbuild from 'rollup-plugin-esbuild'
16
14
  import ts from 'typescript'
17
15
 
18
16
  import { recusiveListFiles } from '#~/utils/recusiveListFiles.ts'
@@ -34,25 +32,35 @@ interface PackageJSON {
34
32
  const {
35
33
  JIEK_ROOT,
36
34
  JIEK_NAME,
35
+ JIEK_BUILDER,
37
36
  JIEK_ENTRIES,
38
37
  JIEK_EXTERNAL,
39
38
  JIEK_WITHOUT_JS,
40
39
  JIEK_WITHOUT_DTS,
41
40
  JIEK_WITHOUT_MINIFY,
41
+ JIEK_MINIFY_TYPE,
42
42
  JIEK_NO_CLEAN,
43
- JIEK_ONLY_MINIFY
43
+ JIEK_ONLY_MINIFY,
44
+ JIEK_TSCONFIG,
45
+ JIEK_DTSCONFIG
44
46
  } = process.env
45
47
 
46
- const entries = JIEK_ENTRIES
47
- ?.split(',')
48
- .map(e => e.trim())
49
- .map(e => ({ 'index': '.' }[e] ?? e))
48
+ const resolveArrayString = (str: string | undefined) => {
49
+ const arr = [
50
+ ...new Set(
51
+ str
52
+ ?.split(',')
53
+ .map(e => e.trim())
54
+ .filter(e => e.length > 0)
55
+ ?? []
56
+ )
57
+ ]
58
+ return arr?.length ? arr : undefined
59
+ }
60
+
61
+ const entries = resolveArrayString(JIEK_ENTRIES)?.map(e => ({ 'index': '.' }[e] ?? e))
50
62
 
51
- const commandExternal = JIEK_EXTERNAL
52
- ?.split(',')
53
- .map(e => e.trim())
54
- .map(e => new RegExp(`^${e}$`))
55
- ?? []
63
+ const commandExternal = resolveArrayString(JIEK_EXTERNAL)?.map(e => new RegExp(`^${e}$`))
56
64
 
57
65
  const WORKSPACE_ROOT = JIEK_ROOT ?? getWorkspaceDir()
58
66
  const COMMON_OPTIONS = {} satisfies RollupOptions
@@ -74,6 +82,18 @@ const MINIFY_DEFAULT_VALUE = WITHOUT_MINIFY
74
82
  ? 'only-minify'
75
83
  : true
76
84
 
85
+ type BuilderOptions = NonNullable<TemplateOptions['builder']>
86
+
87
+ const BUILDER_OPTIONS = {
88
+ type: JIEK_BUILDER ?? 'esbuild'
89
+ } as NonNullable<Exclude<BuilderOptions, string>>
90
+
91
+ type MinifyOptions = NonNullable<TemplateOptions['output']>['minifyOptions']
92
+
93
+ const MINIFY_OPTIONS = {
94
+ type: JIEK_MINIFY_TYPE ?? 'esbuild'
95
+ } as NonNullable<Exclude<MinifyOptions, string>>
96
+
77
97
  const config = loadConfig({
78
98
  root: WORKSPACE_ROOT
79
99
  }) ?? {}
@@ -147,15 +167,37 @@ const reveal = (obj: string | Record<string, unknown>, keys: string[]) =>
147
167
  return acc[key] as string | Record<string, unknown>
148
168
  }, obj)
149
169
 
170
+ const resolveMinifyOptions = (minifyOptions: MinifyOptions): typeof MINIFY_OPTIONS =>
171
+ typeof minifyOptions === 'string'
172
+ ? { type: minifyOptions }
173
+ : minifyOptions ?? { type: 'esbuild' }
174
+
175
+ const resolveBuilderOptions = (
176
+ builder: TemplateOptions['builder']
177
+ ): Exclude<TemplateOptions['builder'], string | undefined> =>
178
+ typeof builder === 'string'
179
+ ? { type: builder }
180
+ : builder ?? { type: 'esbuild' }
181
+
182
+ const resolvedMinifyOptions = resolveMinifyOptions(build.output?.minifyOptions ?? MINIFY_OPTIONS)
183
+ const { type: _resolvedMinifyOptionsType, ...noTypeResolvedMinifyOptions } = resolvedMinifyOptions
184
+ const resolvedBuilderOptions = resolveBuilderOptions(build.builder ?? BUILDER_OPTIONS)
185
+ const { type: _resolvedBuilderOptionsType, ...noTypeResolvedBuilderOptions } = resolvedBuilderOptions
186
+
150
187
  const withMinify = (
151
188
  output: OutputOptions & {
152
189
  plugins?: OutputPlugin[]
153
190
  },
154
191
  minify = build?.output?.minify ?? MINIFY_DEFAULT_VALUE
155
- ): OutputOptions[] =>
156
- minify === false
157
- ? [output]
158
- : minify === 'only-minify'
192
+ ): OutputOptions[] => {
193
+ if (minify === false) return [output]
194
+
195
+ const minifyPlugin = resolvedMinifyOptions.type === 'esbuild'
196
+ ? import('rollup-plugin-esbuild').then(({ minify }) => minify(noTypeResolvedMinifyOptions as any))
197
+ : resolvedMinifyOptions.type === 'swc'
198
+ ? import('rollup-plugin-swc3').then(({ minify }) => minify(noTypeResolvedMinifyOptions as any))
199
+ : import('@rollup/plugin-terser').then(({ default: minify }) => minify(noTypeResolvedMinifyOptions as any))
200
+ return minify === 'only-minify'
159
201
  ? [{
160
202
  ...output,
161
203
  // TODO replace suffix when pubish to npm and the `build.output.minify` is 'only-minify'
@@ -168,7 +210,7 @@ const withMinify = (
168
210
  })(),
169
211
  plugins: [
170
212
  ...(output.plugins ?? []),
171
- terser()
213
+ minifyPlugin
172
214
  ]
173
215
  }]
174
216
  : [
@@ -184,10 +226,11 @@ const withMinify = (
184
226
  file: output.file?.replace(/(\.[cm]?js)$/, '.min$1'),
185
227
  plugins: [
186
228
  ...(output.plugins ?? []),
187
- terser()
229
+ minifyPlugin
188
230
  ]
189
231
  }
190
232
  ]
233
+ }
191
234
 
192
235
  const generateConfigs = (context: ConfigGenerateContext, options: TemplateOptions = {}): RollupOptions[] => {
193
236
  const {
@@ -199,7 +242,7 @@ const generateConfigs = (context: ConfigGenerateContext, options: TemplateOption
199
242
  pkgIsModule,
200
243
  conditionals
201
244
  } = context
202
- const external = [...inputExternal, ...(options.external ?? []), ...commandExternal]
245
+ const external = [...inputExternal, ...(options.external ?? []), ...(commandExternal ?? [])]
203
246
  const isModule = conditionals.includes('import')
204
247
  const isCommonJS = conditionals.includes('require')
205
248
  const isBrowser = conditionals.includes('browser')
@@ -207,10 +250,15 @@ const generateConfigs = (context: ConfigGenerateContext, options: TemplateOption
207
250
  resolveWorkspacePath('tsconfig.json'),
208
251
  resolveWorkspacePath('tsconfig.dts.json')
209
252
  ]
253
+ JIEK_TSCONFIG && dtsTSConfigPaths.push(resolveWorkspacePath(JIEK_TSCONFIG))
254
+ JIEK_DTSCONFIG && dtsTSConfigPaths.push(resolveWorkspacePath(JIEK_DTSCONFIG))
210
255
  const buildTSConfigPaths = [
211
256
  ...dtsTSConfigPaths,
212
257
  resolveWorkspacePath('tsconfig.build.json')
213
258
  ]
259
+ // 这里重复写了俩次 JIEK_TSCONFIG 到 tsconfig 的加载列表中
260
+ // 目的是保证在 build 的时候,JIEK_TSCONFIG 的优先级高于 JIEK_DTSCONFIG
261
+ JIEK_TSCONFIG && buildTSConfigPaths.push(resolveWorkspacePath(JIEK_TSCONFIG))
214
262
  let dtsTSConfigPath: string | undefined
215
263
  dtsTSConfigPaths.forEach(p => {
216
264
  if (fs.existsSync(p) && fs.statSync(p).isFile()) {
@@ -275,6 +323,28 @@ const generateConfigs = (context: ConfigGenerateContext, options: TemplateOption
275
323
  const sourcemap = typeof options?.output?.sourcemap === 'object'
276
324
  ? options.output.sourcemap.js
277
325
  : options?.output?.sourcemap
326
+ const builder = resolvedBuilderOptions.type === 'esbuild'
327
+ ? import('rollup-plugin-esbuild').then(({ default: esbuild }) =>
328
+ esbuild({
329
+ sourceMap: sourcemap === 'hidden' ? false : !!sourcemap,
330
+ tsconfig: buildTSConfigPath,
331
+ ...noTypeResolvedBuilderOptions
332
+ })
333
+ )
334
+ : import('rollup-plugin-swc3').then(({ default: swc }) =>
335
+ swc({
336
+ sourceMaps: typeof sourcemap === 'boolean'
337
+ ? sourcemap
338
+ : typeof sourcemap === 'undefined'
339
+ ? undefined
340
+ : ({
341
+ hidden: false,
342
+ inline: 'inline'
343
+ } as const)[sourcemap] ?? undefined,
344
+ tsconfig: buildTSConfigPath,
345
+ ...noTypeResolvedBuilderOptions
346
+ })
347
+ )
278
348
  rollupOptions.push({
279
349
  input: inputObj,
280
350
  external,
@@ -314,10 +384,7 @@ const generateConfigs = (context: ConfigGenerateContext, options: TemplateOption
314
384
  })
315
385
  )
316
386
  .catch(() => void 0),
317
- esbuild({
318
- sourceMap: sourcemap === 'hidden' ? false : !!sourcemap,
319
- tsconfig: buildTSConfigPath
320
- }),
387
+ builder,
321
388
  commonjs(),
322
389
  progress({
323
390
  onEvent: (event, message) =>
@@ -389,20 +456,22 @@ const generateConfigs = (context: ConfigGenerateContext, options: TemplateOption
389
456
  ]
390
457
  })
391
458
  }
392
- // only push the first one a watcher plugin
393
- rollupOptions[0].plugins = [
394
- {
395
- name: 'jiek-plugin-watcher',
396
- watchChange: (id) =>
397
- sendMessage(
398
- {
399
- type: 'watchChange',
400
- data: { id, name: JIEK_NAME!, path, input }
401
- } satisfies RollupProgressEvent
402
- )
403
- },
404
- ...(rollupOptions[0].plugins as any)
405
- ]
459
+ if (rollupOptions.length > 0) {
460
+ // only push the first one a watcher plugin
461
+ rollupOptions[0].plugins = [
462
+ {
463
+ name: 'jiek-plugin-watcher',
464
+ watchChange: (id) =>
465
+ sendMessage(
466
+ {
467
+ type: 'watchChange',
468
+ data: { id, name: JIEK_NAME!, path, input }
469
+ } satisfies RollupProgressEvent
470
+ )
471
+ },
472
+ ...(rollupOptions[0].plugins as any)
473
+ ]
474
+ }
406
475
  return rollupOptions
407
476
  }
408
477