jiek 1.1.12 → 2.0.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -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,13 +32,36 @@ interface PackageJSON {
34
32
  const {
35
33
  JIEK_ROOT,
36
34
  JIEK_NAME,
35
+ JIEK_BUILDER,
37
36
  JIEK_ENTRIES,
37
+ JIEK_EXTERNAL,
38
38
  JIEK_WITHOUT_JS,
39
39
  JIEK_WITHOUT_DTS,
40
40
  JIEK_WITHOUT_MINIFY,
41
+ JIEK_MINIFY_TYPE,
41
42
  JIEK_NO_CLEAN,
42
- JIEK_ONLY_MINIFY
43
+ JIEK_ONLY_MINIFY,
44
+ JIEK_TSCONFIG,
45
+ JIEK_DTSCONFIG
43
46
  } = process.env
47
+
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))
62
+
63
+ const commandExternal = resolveArrayString(JIEK_EXTERNAL)?.map(e => new RegExp(`^${e}$`))
64
+
44
65
  const WORKSPACE_ROOT = JIEK_ROOT ?? getWorkspaceDir()
45
66
  const COMMON_OPTIONS = {} satisfies RollupOptions
46
67
  const COMMON_PLUGINS = [
@@ -61,6 +82,18 @@ const MINIFY_DEFAULT_VALUE = WITHOUT_MINIFY
61
82
  ? 'only-minify'
62
83
  : true
63
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
+
64
97
  const config = loadConfig({
65
98
  root: WORKSPACE_ROOT
66
99
  }) ?? {}
@@ -134,15 +167,37 @@ const reveal = (obj: string | Record<string, unknown>, keys: string[]) =>
134
167
  return acc[key] as string | Record<string, unknown>
135
168
  }, obj)
136
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
+
137
187
  const withMinify = (
138
188
  output: OutputOptions & {
139
189
  plugins?: OutputPlugin[]
140
190
  },
141
191
  minify = build?.output?.minify ?? MINIFY_DEFAULT_VALUE
142
- ): OutputOptions[] =>
143
- minify === false
144
- ? [output]
145
- : 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'
146
201
  ? [{
147
202
  ...output,
148
203
  // TODO replace suffix when pubish to npm and the `build.output.minify` is 'only-minify'
@@ -155,7 +210,7 @@ const withMinify = (
155
210
  })(),
156
211
  plugins: [
157
212
  ...(output.plugins ?? []),
158
- terser()
213
+ minifyPlugin
159
214
  ]
160
215
  }]
161
216
  : [
@@ -171,10 +226,11 @@ const withMinify = (
171
226
  file: output.file?.replace(/(\.[cm]?js)$/, '.min$1'),
172
227
  plugins: [
173
228
  ...(output.plugins ?? []),
174
- terser()
229
+ minifyPlugin
175
230
  ]
176
231
  }
177
232
  ]
233
+ }
178
234
 
179
235
  const generateConfigs = (context: ConfigGenerateContext, options: TemplateOptions = {}): RollupOptions[] => {
180
236
  const {
@@ -182,10 +238,11 @@ const generateConfigs = (context: ConfigGenerateContext, options: TemplateOption
182
238
  name,
183
239
  input,
184
240
  output,
185
- external,
241
+ external: inputExternal,
186
242
  pkgIsModule,
187
243
  conditionals
188
244
  } = context
245
+ const external = [...inputExternal, ...(options.external ?? []), ...(commandExternal ?? [])]
189
246
  const isModule = conditionals.includes('import')
190
247
  const isCommonJS = conditionals.includes('require')
191
248
  const isBrowser = conditionals.includes('browser')
@@ -193,12 +250,27 @@ const generateConfigs = (context: ConfigGenerateContext, options: TemplateOption
193
250
  resolveWorkspacePath('tsconfig.json'),
194
251
  resolveWorkspacePath('tsconfig.dts.json')
195
252
  ]
253
+ JIEK_TSCONFIG && dtsTSConfigPaths.push(resolveWorkspacePath(JIEK_TSCONFIG))
254
+ JIEK_DTSCONFIG && dtsTSConfigPaths.push(resolveWorkspacePath(JIEK_DTSCONFIG))
255
+ const buildTSConfigPaths = [
256
+ ...dtsTSConfigPaths,
257
+ resolveWorkspacePath('tsconfig.build.json')
258
+ ]
259
+ // 这里重复写了俩次 JIEK_TSCONFIG 到 tsconfig 的加载列表中
260
+ // 目的是保证在 build 的时候,JIEK_TSCONFIG 的优先级高于 JIEK_DTSCONFIG
261
+ JIEK_TSCONFIG && buildTSConfigPaths.push(resolveWorkspacePath(JIEK_TSCONFIG))
196
262
  let dtsTSConfigPath: string | undefined
197
263
  dtsTSConfigPaths.forEach(p => {
198
264
  if (fs.existsSync(p) && fs.statSync(p).isFile()) {
199
265
  dtsTSConfigPath = p
200
266
  }
201
267
  })
268
+ let buildTSConfigPath: string | undefined
269
+ buildTSConfigPaths.forEach(p => {
270
+ if (fs.existsSync(p) && fs.statSync(p).isFile()) {
271
+ buildTSConfigPath = p
272
+ }
273
+ })
202
274
  let compilerOptions: ts.CompilerOptions = {}
203
275
  if (dtsTSConfigPath) {
204
276
  const jsonCompilerOptions = getCompilerOptionsByFilePath(dtsTSConfigPath, resolve(input))
@@ -248,6 +320,31 @@ const generateConfigs = (context: ConfigGenerateContext, options: TemplateOption
248
320
 
249
321
  const commonPlugins: Plugin[] = []
250
322
  if (jsOutput && !WITHOUT_JS) {
323
+ const sourcemap = typeof options?.output?.sourcemap === 'object'
324
+ ? options.output.sourcemap.js
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
+ )
251
348
  rollupOptions.push({
252
349
  input: inputObj,
253
350
  external,
@@ -263,9 +360,7 @@ const generateConfigs = (context: ConfigGenerateContext, options: TemplateOption
263
360
  .replace(/(\.[cm]?)ts$/, jsOutputSuffix)
264
361
  : output.replace(`${jsOutdir}/`, '')
265
362
  ),
266
- sourcemap: typeof options?.output?.sourcemap === 'object'
267
- ? options.output.sourcemap.js
268
- : options?.output?.sourcemap,
363
+ sourcemap,
269
364
  format: isModule ? 'esm' : (
270
365
  isCommonJS ? 'cjs' : (
271
366
  isBrowser ? 'umd' : (
@@ -289,9 +384,7 @@ const generateConfigs = (context: ConfigGenerateContext, options: TemplateOption
289
384
  })
290
385
  )
291
386
  .catch(() => void 0),
292
- esbuild({
293
- tsconfig: dtsTSConfigPath
294
- }),
387
+ builder,
295
388
  commonjs(),
296
389
  progress({
297
390
  onEvent: (event, message) =>
@@ -338,7 +431,6 @@ const generateConfigs = (context: ConfigGenerateContext, options: TemplateOption
338
431
  dts({
339
432
  respectExternal: true,
340
433
  compilerOptions: {
341
- ...compilerOptions,
342
434
  // temp directory, it not affect the output
343
435
  // but if the user not set it and `declaration`, inputs can't generate any dts files when the input relative imports of `package.json`
344
436
  outDir: 'dist',
@@ -348,7 +440,8 @@ const generateConfigs = (context: ConfigGenerateContext, options: TemplateOption
348
440
  // Expected '{', got 'type' (Note that you need plugins to import files that are not JavaScript)
349
441
  // https://github.com/Swatinem/rollup-plugin-dts/issues/96
350
442
  noEmit: false
351
- }
443
+ },
444
+ tsconfig: dtsTSConfigPath
352
445
  }),
353
446
  progress({
354
447
  onEvent: (event, message) =>
@@ -363,20 +456,22 @@ const generateConfigs = (context: ConfigGenerateContext, options: TemplateOption
363
456
  ]
364
457
  })
365
458
  }
366
- // only push the first one a watcher plugin
367
- rollupOptions[0].plugins = [
368
- {
369
- name: 'jiek-plugin-watcher',
370
- watchChange: (id) =>
371
- sendMessage(
372
- {
373
- type: 'watchChange',
374
- data: { id, name: JIEK_NAME!, path, input }
375
- } satisfies RollupProgressEvent
376
- )
377
- },
378
- ...(rollupOptions[0].plugins as any)
379
- ]
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
+ }
380
475
  return rollupOptions
381
476
  }
382
477
 
@@ -386,13 +481,6 @@ export function template(packageJSON: PackageJSON): RollupOptions[] {
386
481
  if (!name) throw new Error('package.json name is required')
387
482
  if (!entrypoints) throw new Error('package.json exports is required')
388
483
 
389
- const entries = JIEK_ENTRIES
390
- ?.split(',')
391
- .map(e => e.trim())
392
- .map(e => ({
393
- 'index': '.'
394
- }[e] ?? e))
395
-
396
484
  const packageName = pascalCase(name)
397
485
 
398
486
  const external = externalResolver(packageJSON as Record<string, unknown>)
@@ -6,8 +6,8 @@ import { filterPackagesFromDir } from '@pnpm/filter-workspace-packages'
6
6
  import { program } from 'commander'
7
7
  import { load } from 'js-yaml'
8
8
 
9
- import { getRoot } from './getRoot'
10
- import { getWD } from './getWD'
9
+ import { getRoot } from '#~/utils/getRoot.ts'
10
+ import { getWD } from '#~/utils/getWD.ts'
11
11
 
12
12
  export let type = ''
13
13
 
@@ -16,10 +16,6 @@ try {
16
16
  require.resolve('@pnpm/filter-workspace-packages')
17
17
  type = 'pnpm'
18
18
  } catch { /* empty */ }
19
- if (type !== '') {
20
- program
21
- .option('-f, --filter <filter>', 'filter packages, support fuzzy match and array. e.g. -f core,utils')
22
- }
23
19
 
24
20
  export interface ProjectsGraph {
25
21
  wd: string
@@ -1,34 +0,0 @@
1
- import type { Plugin, PluginImpl } from 'rollup'
2
-
3
- import globalResolver from '../utils/globalResolver'
4
-
5
- interface GlobalsOptions {
6
- external?: (string | RegExp)[]
7
- }
8
-
9
- export function createGlobalsLinkage() {
10
- let globals = {}
11
- const dependencies = new Set<string>([])
12
- return [
13
- (({ external } = {}) => {
14
- return {
15
- name: 'globals',
16
- resolveId(id) {
17
- if (external?.some(dep => dep instanceof RegExp ? dep.test(id) : dep === id)) {
18
- dependencies.add(id)
19
- return { id, external: true }
20
- }
21
- return null
22
- },
23
- outputOptions(options) {
24
- globals = [...dependencies].reduce((acc, value) => ({
25
- ...acc,
26
- [value]: globalResolver(value)
27
- }), {})
28
- return { ...options, globals }
29
- }
30
- }
31
- }) as PluginImpl<GlobalsOptions>,
32
- { outputOptions: options => ({ ...options, globals }) } as Plugin
33
- ] as const
34
- }