From 68a8331f7a9425c18a4a417488bbc867d3ea7332 Mon Sep 17 00:00:00 2001 From: XGHeaven Date: Fri, 3 Apr 2026 11:54:39 +0800 Subject: [PATCH] refactor: use rollup to compile transform mode --- .changeset/four-meals-cough.md | 5 + packages/pkg/src/config/schema.ts | 1 + packages/pkg/src/core/init.ts | 5 +- packages/pkg/src/engine/rollup/build.ts | 20 +- packages/pkg/src/engine/rollup/output.ts | 52 ++ packages/pkg/src/engine/rollup/warn.ts | 25 + .../src/helpers/__tests__/getTaskIO.test.ts | 23 - packages/pkg/src/helpers/getTaskIO.ts | 51 +- packages/pkg/src/helpers/pluginContainer.ts | 665 ------------------ packages/pkg/src/rollupPlugins/swc.ts | 8 +- packages/pkg/src/tasks/transform.ts | 405 +++++++---- packages/pkg/src/types.ts | 17 + packages/pkg/tests/core/init.test.ts | 81 +++ packages/pkg/tests/helpers/getTaskIO.test.ts | 65 ++ pnpm-lock.yaml | 6 + tests/helpers/watch.ts | 208 ++++++ .../alias/__snapshots__/index.test.ts.snap | 30 +- .../default/__snapshots__/index.test.ts.snap | 8 +- .../helpers/__snapshots__/index.test.ts.snap | 17 +- .../__snapshots__/index.test.ts.snap | 50 +- .../plugins/__snapshots__/index.test.ts.snap | 24 +- .../react/__snapshots__/index.test.ts.snap | 32 +- .../__snapshots__/index.test.ts.snap | 218 ++++++ .../transform/build.config.watch-test.mts | 14 + tests/integration/transform/index.test.ts | 149 ++++ tests/integration/transform/package.json | 8 + .../transform/src-multi-right/entry.ts | 3 + .../transform/src-multi-right/nested/label.ts | 1 + .../integration/transform/src/docs/readme.md | 3 + tests/integration/transform/src/ext-cjs.cjs | 1 + tests/integration/transform/src/ext-cts.cts | 1 + tests/integration/transform/src/ext-jsx.jsx | 1 + tests/integration/transform/src/ext-mjs.mjs | 1 + tests/integration/transform/src/ext-mts.mts | 1 + tests/integration/transform/src/ext-tsx.tsx | 1 + .../integration/transform/src/ext-types.d.ts | 3 + tests/integration/transform/src/logic.ts | 1 + tests/integration/transform/src/main.ts | 5 + tests/integration/transform/src/meta.yaml | 2 + .../integration/transform/src/skip.ignore.txt | 1 + .../transform/src/styles/copy.less | 5 + .../transform/src/styles/copy.scss | 5 + website/docs/guide/abilities.md | 41 +- website/docs/reference/config.md | 160 +++-- 44 files changed, 1456 insertions(+), 967 deletions(-) create mode 100644 .changeset/four-meals-cough.md create mode 100644 packages/pkg/src/engine/rollup/output.ts create mode 100644 packages/pkg/src/engine/rollup/warn.ts delete mode 100644 packages/pkg/src/helpers/__tests__/getTaskIO.test.ts delete mode 100644 packages/pkg/src/helpers/pluginContainer.ts create mode 100644 packages/pkg/tests/helpers/getTaskIO.test.ts create mode 100644 tests/helpers/watch.ts create mode 100644 tests/integration/transform/__snapshots__/index.test.ts.snap create mode 100644 tests/integration/transform/build.config.watch-test.mts create mode 100644 tests/integration/transform/index.test.ts create mode 100644 tests/integration/transform/package.json create mode 100644 tests/integration/transform/src-multi-right/entry.ts create mode 100644 tests/integration/transform/src-multi-right/nested/label.ts create mode 100644 tests/integration/transform/src/docs/readme.md create mode 100644 tests/integration/transform/src/ext-cjs.cjs create mode 100644 tests/integration/transform/src/ext-cts.cts create mode 100644 tests/integration/transform/src/ext-jsx.jsx create mode 100644 tests/integration/transform/src/ext-mjs.mjs create mode 100644 tests/integration/transform/src/ext-mts.mts create mode 100644 tests/integration/transform/src/ext-tsx.tsx create mode 100644 tests/integration/transform/src/ext-types.d.ts create mode 100644 tests/integration/transform/src/logic.ts create mode 100644 tests/integration/transform/src/main.ts create mode 100644 tests/integration/transform/src/meta.yaml create mode 100644 tests/integration/transform/src/skip.ignore.txt create mode 100644 tests/integration/transform/src/styles/copy.less create mode 100644 tests/integration/transform/src/styles/copy.scss diff --git a/.changeset/four-meals-cough.md b/.changeset/four-meals-cough.md new file mode 100644 index 00000000..ef171409 --- /dev/null +++ b/.changeset/four-meals-cough.md @@ -0,0 +1,5 @@ +--- +'@ice/pkg': major +--- + +refactor: use rollup to compile transform mode diff --git a/packages/pkg/src/config/schema.ts b/packages/pkg/src/config/schema.ts index 3b252e5e..e78ae393 100644 --- a/packages/pkg/src/config/schema.ts +++ b/packages/pkg/src/config/schema.ts @@ -3,6 +3,7 @@ import { z } from 'zod'; export const transformSchema = z.object({ formats: z.string().array().optional(), excludes: z.union([z.string(), z.array(z.string())]).optional(), + entryRoot: z.string().optional(), }); export const bundleSchema = z.object({ diff --git a/packages/pkg/src/core/init.ts b/packages/pkg/src/core/init.ts index 4e3886da..7d114762 100644 --- a/packages/pkg/src/core/init.ts +++ b/packages/pkg/src/core/init.ts @@ -1,5 +1,5 @@ import { AliasBundleFormatString, BuildTask, BundleUserConfig, Context, DeclarationUserConfig } from '../types.js'; -import { formatEntry, getTransformDefaultOutputDir } from '../helpers/getTaskIO.js'; +import { formatEntry, getTransformDefaultOutputDir, getTransformEntryRoot } from '../helpers/getTaskIO.js'; import { stringifyObject } from '../utils.js'; import { merge, mergeWith, omit } from 'es-toolkit/object'; import path, { resolve } from 'node:path'; @@ -124,6 +124,9 @@ export function initTask(buildTask: BuildTask, options: InitTaskOptions) { mergeDefaults(config, defaultBundleUserConfig); } else if (config.type === 'transform') { config.modes ??= [expectedMode]; + config.excludes ??= userConfig.transform?.excludes; + config.entryRoot ??= pkg?.entryRoot ?? userConfig.transform?.entryRoot; + config.entryRoot = getTransformEntryRoot(rootDir, config.entry as Record, config.entryRoot); config.outputDir ??= pkg?.outputDir ?? getTransformDefaultOutputDir(rootDir, taskName, config); config.outputDir = resolve(rootDir, config.outputDir!); } else if (config.type === 'declaration') { diff --git a/packages/pkg/src/engine/rollup/build.ts b/packages/pkg/src/engine/rollup/build.ts index 0a7cf178..1a85d96e 100644 --- a/packages/pkg/src/engine/rollup/build.ts +++ b/packages/pkg/src/engine/rollup/build.ts @@ -1,14 +1,7 @@ -import * as path from 'path'; import * as rollup from 'rollup'; import { toArray } from '../../utils.js'; -import type { - OutputAsset as RollupOutputAsset, - OutputChunk as RollupOutputChunk, - OutputOptions, - RollupBuild, - RollupOptions, - RollupOutput, -} from 'rollup'; +import { toOutputFiles } from './output.js'; +import type { OutputOptions, RollupBuild, RollupOptions, RollupOutput } from 'rollup'; import type { OutputFile, OutputResult, TaskRunnerContext } from '../../types.js'; export async function build(rollupOptions: RollupOptions, taskRunnerContext: TaskRunnerContext): Promise { @@ -42,14 +35,7 @@ export async function writeFiles( for (let o = 0; o < rollupOutputOptions.length; ++o) { const writeResult = await write(rollupOutputOptions[o]); const distDir = rollupOutputOptions[o].dir ?? ''; - writeResult.output.forEach((chunk: RollupOutputChunk | RollupOutputAsset) => { - outputFiles.push({ - absolutePath: 'facadeModuleId' in chunk ? chunk.facadeModuleId! : undefined, - dest: path.join(distDir ?? '', chunk.fileName ?? ''), - filename: chunk.fileName, - code: chunk.type === 'chunk' ? chunk.code : chunk.source, - }); - }); + outputFiles.push(...toOutputFiles(writeResult.output, distDir)); outputs.push(writeResult.output); } diff --git a/packages/pkg/src/engine/rollup/output.ts b/packages/pkg/src/engine/rollup/output.ts new file mode 100644 index 00000000..06c5840a --- /dev/null +++ b/packages/pkg/src/engine/rollup/output.ts @@ -0,0 +1,52 @@ +import * as path from 'path'; +import type { OutputAsset as RollupOutputAsset, OutputChunk as RollupOutputChunk } from 'rollup'; +import type { OutputFile } from '../../types.js'; + +type RollupOutputItem = RollupOutputChunk | RollupOutputAsset; + +export interface NormalizedRollupOutputItem { + type: 'chunk' | 'asset'; + fileName: string; + dest: string; + absolutePath?: string; + code?: string | Uint8Array; + chunk?: RollupOutputChunk; + asset?: RollupOutputAsset; +} + +interface ToOutputFilesOptions { + map?: (item: NormalizedRollupOutputItem) => Partial; +} + +function normalizeOutputItem(item: RollupOutputItem, distDir: string): NormalizedRollupOutputItem { + return { + type: item.type, + fileName: item.fileName, + dest: path.join(distDir, item.fileName ?? ''), + absolutePath: 'facadeModuleId' in item ? (item.facadeModuleId ?? undefined) : undefined, + code: item.type === 'chunk' ? item.code : item.source, + chunk: item.type === 'chunk' ? item : undefined, + asset: item.type === 'asset' ? item : undefined, + }; +} + +export function toOutputFile(item: RollupOutputItem, distDir: string, options: ToOutputFilesOptions = {}): OutputFile { + const normalized = normalizeOutputItem(item, distDir); + const base: OutputFile = { + filePath: normalized.fileName, + absolutePath: normalized.absolutePath, + ext: path.extname(normalized.fileName), + dest: normalized.dest, + filename: normalized.fileName, + code: normalized.code, + map: normalized.chunk?.map ?? undefined, + }; + return { + ...base, + ...(options.map?.(normalized) ?? {}), + }; +} + +export function toOutputFiles(items: RollupOutputItem[], distDir: string, options: ToOutputFilesOptions = {}) { + return items.map((item) => toOutputFile(item, distDir, options)); +} diff --git a/packages/pkg/src/engine/rollup/warn.ts b/packages/pkg/src/engine/rollup/warn.ts new file mode 100644 index 00000000..d6f2ecca --- /dev/null +++ b/packages/pkg/src/engine/rollup/warn.ts @@ -0,0 +1,25 @@ +import type { RollupLog, RollupOptions, WarningHandlerWithDefault } from 'rollup'; + +function isIgnorableWarning(warning: RollupLog) { + return warning.code === 'EMPTY_BUNDLE' || warning.message.includes('Generated an empty chunk'); +} + +export function withFilteredRollupWarnings(rollupOptions: RollupOptions): RollupOptions { + const onwarn = rollupOptions.onwarn; + const filteredOnwarn: WarningHandlerWithDefault = (warning, defaultHandler) => { + if (isIgnorableWarning(warning)) { + return; + } + + if (onwarn) { + onwarn(warning, defaultHandler); + } else { + defaultHandler(warning); + } + }; + + return { + ...rollupOptions, + onwarn: filteredOnwarn, + }; +} diff --git a/packages/pkg/src/helpers/__tests__/getTaskIO.test.ts b/packages/pkg/src/helpers/__tests__/getTaskIO.test.ts deleted file mode 100644 index 6b6dc0d8..00000000 --- a/packages/pkg/src/helpers/__tests__/getTaskIO.test.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { test, expect } from 'vitest'; -import { formatEntry } from '../getTaskIO.js'; - -test('formatEntry', () => { - expect(formatEntry('src/index')).toEqual({ - index: 'src/index', - }); - - expect(formatEntry(['src/index', 'src/client'])).toEqual({ - index: 'src/index', - client: 'src/client', - }); - - expect( - formatEntry({ - index: 'src/index', - client: 'src/client', - }), - ).toEqual({ - index: 'src/index', - client: 'src/client', - }); -}); diff --git a/packages/pkg/src/helpers/getTaskIO.ts b/packages/pkg/src/helpers/getTaskIO.ts index 99681568..5532d43e 100644 --- a/packages/pkg/src/helpers/getTaskIO.ts +++ b/packages/pkg/src/helpers/getTaskIO.ts @@ -1,4 +1,4 @@ -import { isAbsolute, resolve, join } from 'node:path'; +import { isAbsolute, resolve, join, relative, dirname } from 'node:path'; import { TransformTaskConfig } from '../types.js'; export function formatEntry(inputEntry?: string | string[] | Record): Record { @@ -35,6 +35,55 @@ export const getTransformEntryDirs = (rootDir: string, entry: Record { + if (!paths.length) { + return ''; + } + + let commonPath = resolve(paths[0]); + + for (let i = 1; i < paths.length; i++) { + const currentPath = resolve(paths[i]); + + while (!isPathInDir(currentPath, commonPath)) { + const parentPath = dirname(commonPath); + if (parentPath === commonPath) { + break; + } + commonPath = parentPath; + } + } + + return commonPath; +}; + +export const getTransformEntryRoot = (rootDir: string, entry: Record, configuredEntryRoot?: string) => { + const entryDirs = getTransformEntryDirs(rootDir, entry); + const autoEntryRoot = entryDirs.length ? getCommonAncestorDir(entryDirs) : resolve(rootDir); + + if (!configuredEntryRoot) { + return autoEntryRoot; + } + + const resolvedEntryRoot = isAbsolute(configuredEntryRoot) + ? configuredEntryRoot + : resolve(rootDir, configuredEntryRoot); + const invalidEntryDir = entryDirs.find((entryDir) => !isPathInDir(entryDir, resolvedEntryRoot)); + + if (invalidEntryDir) { + throw new Error( + `Invalid entryRoot "${configuredEntryRoot}". Expected a common ancestor of all transform entries, but "${invalidEntryDir}" is outside it.`, + ); + } + + return resolvedEntryRoot; +}; + +function isPathInDir(filePath: string, dirPath: string) { + const relativePath = relative(resolve(dirPath), resolve(filePath)); + return relativePath === '' || (!relativePath.startsWith('..') && !isAbsolute(relativePath)); +} + export const getTransformDefaultOutputDir = (rootDir: string, taskName: string, config: TransformTaskConfig) => { if (config.pkg) { return resolve(rootDir, config.pkg.id); diff --git a/packages/pkg/src/helpers/pluginContainer.ts b/packages/pkg/src/helpers/pluginContainer.ts deleted file mode 100644 index a75f0fdf..00000000 --- a/packages/pkg/src/helpers/pluginContainer.ts +++ /dev/null @@ -1,665 +0,0 @@ -import { consola } from 'consola'; -import fs from 'fs-extra'; -import { resolve, join, isAbsolute } from 'path'; -import type { - InputOptions, - MinimalPluginContext, - OutputOptions, - ModuleInfo, - NormalizedInputOptions, - PartialResolvedId, - ResolvedId, - PluginContext as RollupPluginContext, - LoadResult, - SourceDescription, - EmittedFile, - SourceMap, - RollupError, - TransformResult, - Plugin, - RollupOptions, - ObjectHook, -} from 'rollup'; -import * as acorn from 'acorn'; -import { - combineSourcemaps, - ensureWatchedFile, - generateCodeFrame, - isObject, - isExternalUrl, - normalizePath, - numberToPos, - timeFrom, - createDebugger, - safeRequire, - require, -} from '../utils.js'; -import MagicString from 'magic-string'; -import type { FSWatcher } from 'chokidar'; -import colors from 'picocolors'; -import { performance } from 'perf_hooks'; -import { SourceMapConsumer } from 'source-map'; -import type * as postcss from 'postcss'; -import { createLogger } from './logger.js'; - -export const FS_PREFIX = '/@fs/'; - -interface SourceMapV3 { - file?: string | null; - names: string[]; - sourceRoot?: string; - sources: Array; - sourcesContent?: Array; - version: 3; -} - -// copy from https://unpkg.com/browse/@ampproject/remapping@2.0.3/dist/types/types.d.ts -export interface RawSourceMap extends SourceMapV3 { - mappings: string; -} - -export interface PluginContainerOptions { - cwd?: string; - output?: OutputOptions; - modules?: Map; - writeFile?: (name: string, source: string | Uint8Array) => void; -} - -export interface PluginContainer { - options: InputOptions; - getModuleInfo: (id: string) => ModuleInfo | null; - buildStart: (options: InputOptions) => Promise; - resolveId: ( - id: string, - importer?: string, - options?: { - skip?: Set; - }, - ) => Promise; - transform: ( - code: string, - id: string, - options?: { - inMap?: SourceDescription['map']; - }, - ) => Promise; - load: ( - id: string, - options?: { - ssr?: boolean; - }, - ) => Promise; - close: () => Promise; -} - -type PluginContext = Omit< - RollupPluginContext, - // not documented - | 'cache' - // deprecated - | 'emitAsset' - | 'emitChunk' - | 'getAssetFileName' - | 'getChunkFileName' - | 'isExternal' - | 'moduleIds' - | 'resolveId' - | 'load' ->; - -export let parser = acorn.Parser; - -export async function createPluginContainer( - { - plugins = [], - logger, - root, - output, - build: { rollupOptions }, - }: { - plugins: Plugin[]; - root: string; - output: string; - logger: any; - build: { - rollupOptions: RollupOptions; - }; - }, - moduleGraph?: any, - watcher?: FSWatcher, -): Promise { - let ids = 0; // counter for generating unique emitted asset IDs - const files = new Map< - string, - { - id: string; - name?: string; - filename?: string; - type?: string; - source?: string | Uint8Array; - } - >(); - - const isDebug = process.env.DEBUG; - - const seenResolves: Record = {}; - - const debugResolve = createLogger('resolve'); - const debugPluginResolve = createDebugger('plugin-resolve'); - const debugPluginTransform = createDebugger('plugin-transform'); - - const watchFiles = new Set(); - - // get rollup version - const rollupPkgPath = resolve(require.resolve('rollup'), '../../package.json'); - // new vite pollute types of rollup, should restore it - const minimalContext: Omit & { - meta?: Omit; - } = { - meta: { - rollupVersion: safeRequire(rollupPkgPath).version, - // rollupVersion: '2.3.4', - watchMode: true, - }, - debug: (..._args: unknown[]) => {}, - error: (e: unknown) => { - if (e instanceof Error) throw e; - throw new Error(String(e)); - }, - info: (..._args: unknown[]) => {}, - warn: (..._args: unknown[]) => {}, - }; - - function warnIncompatibleMethod(method: string, plugin: string) { - logger.warn( - colors.cyan(`[plugin:${plugin}] `) + - colors.yellow( - `context method ${colors.bold( - `${method}()`, - )} is not supported in serve mode. This plugin is likely not vite-compatible.`, - ), - ); - } - - // throw when an unsupported ModuleInfo property is accessed, - // so that incompatible plugins fail in a non-cryptic way. - const ModuleInfoProxy: ProxyHandler = { - get(info: any, key: string) { - if (key in info) { - return info[key]; - } - throw Error(`[vite] The "${key}" property of ModuleInfo is not supported.`); - }, - }; - - // same default value of "moduleInfo.meta" as in Rollup - const EMPTY_OBJECT = Object.freeze({}); - - function getModuleInfo(id: string) { - const module = moduleGraph?.getModuleById(id); - if (!module) { - return null; - } - if (!module.info) { - module.info = new Proxy({ id, meta: module.meta || EMPTY_OBJECT } as ModuleInfo, ModuleInfoProxy); - } - return module.info; - } - - function updateModuleInfo(id: string, { meta }: { meta?: object | null }) { - if (meta) { - const moduleInfo = getModuleInfo(id); - if (moduleInfo) { - moduleInfo.meta = { ...moduleInfo.meta, ...meta }; - } - } - } - - // we should create a new context for each async hook pipeline so that the - // active plugin in that pipeline can be tracked in a concurrency-safe manner. - // using a class to make creating new contexts more efficient - // NOTE: intentionally not implementing PluginContext exactly to allow gradual typing - class Context { - meta = minimalContext.meta; - ssr = false; - _activePlugin: Plugin | null; - _activeId: string | null = null; - _activeCode: string | null = null; - _resolveSkips?: Set; - _addedImports: Set | null = null; - - constructor(initialPlugin?: Plugin) { - this._activePlugin = initialPlugin || null; - } - - debug(..._args: unknown[]) {} - - info(..._args: unknown[]) {} - - parse(code: string, opts: any = {}) { - return parser.parse(code, { - sourceType: 'module', - ecmaVersion: 'latest', - locations: true, - ...opts, - }) as ReturnType; - } - - async resolve(id: string, importer?: string, options?: { skipSelf?: boolean }) { - let skip: Set | undefined; - if (options?.skipSelf && this._activePlugin) { - skip = new Set(this._resolveSkips); - skip.add(this._activePlugin); - } - let out = await container.resolveId(id, importer, { skip }); - if (typeof out === 'string') out = { id: out }; - return out as ResolvedId | null; - } - - getModuleInfo(id: string) { - return getModuleInfo(id); - } - - getModuleIds() { - return moduleGraph ? moduleGraph.idToModuleMap.keys() : Array.prototype[Symbol.iterator](); - } - - addWatchFile(id: string) { - watchFiles.add(id); - (this._addedImports || (this._addedImports = new Set())).add(id); - if (watcher) ensureWatchedFile(watcher, id, root); - } - - getWatchFiles() { - return [...watchFiles]; - } - - emitFile(assetOrFile: EmittedFile) { - function resolveFileName(fileName?: string) { - if (!fileName) return; - if (isAbsolute(fileName)) return fileName; - return resolve(root, output, fileName); - } - - // TODO: improve this - const name = - assetOrFile.type === 'chunk' - ? assetOrFile.name || assetOrFile.id - : assetOrFile.type === 'asset' - ? assetOrFile.name - : assetOrFile.fileName; - const source = assetOrFile.type === 'asset' ? assetOrFile.source : undefined; - const filename = resolveFileName(assetOrFile.fileName); - - const id = String(++ids); - files.set(id, { id, name, filename }); - - if (assetOrFile.type === 'chunk') { - consola.warn( - `type ${assetOrFile.type} of this.emitFile is not supported in transform mode. This plugin is likely not compatible`, - ); - } else if (source && filename) { - fs.writeFileSync(filename, source as any); - } - return id; - } - - setAssetSource(assetId: string, source: string | Uint8Array) { - const asset = files.get(assetId); - if (!asset) return; - if (asset.type === 'chunk') { - return; - } - asset.source = source; - if (asset.filename) fs.writeFile(asset.filename, source); - } - - getFileName() { - warnIncompatibleMethod('getFileName', this._activePlugin!.name); - return ''; - } - - warn(e: string | RollupError, position?: number | { column: number; line: number }) { - const err = formatError(e, position, this); - const msg = err.message; - // const msg = buildErrorMessage( - // err, - // [colors.yellow(`warning: ${err.message}`)], - // false, - // ); - logger.warn(msg, { - clear: true, - timestamp: true, - }); - } - - error(e: string | RollupError, position?: number | { column: number; line: number }): never { - // error thrown here is caught by the transform middleware and passed on - // the the error middleware. - throw formatError(e, position, this); - } - } - - function formatError( - e: string | RollupError, - position: number | { column: number; line: number } | undefined, - ctx: Context, - ) { - const err = (typeof e === 'string' ? new Error(e) : e) as postcss.CssSyntaxError & RollupError; - - if (err.file && err.name === 'CssSyntaxError') { - err.id = normalizePath(err.file); - } - if (ctx._activePlugin) err.plugin = ctx._activePlugin.name; - if (ctx._activeId && !err.id) err.id = ctx._activeId; - - if (ctx._activeCode && !err.pluginCode) { - err.pluginCode = ctx._activeCode; - - const pos = - position != null - ? position - : err.pos != null - ? err.pos - : // some rollup plugins, e.g. json, sets position instead of pos - (err as any).position; - - if (pos != null) { - let errLocation; - try { - errLocation = numberToPos(ctx._activeCode, pos); - } catch (err2) { - const _err2: any = err2; - logger.error( - colors.red(`Error in error handler:\n${_err2.stack || _err2.message}\n`), - // print extra newline to separate the two errors - { error: _err2 }, - ); - throw err; - } - err.loc = err.loc || { - file: err.id, - ...errLocation, - }; - err.frame = err.frame || generateCodeFrame(ctx._activeCode, pos); - } else if (err.loc) { - // css preprocessors may report errors in an included file - if (!err.frame) { - let code = ctx._activeCode; - if (err.loc.file) { - err.id = normalizePath(err.loc.file); - try { - code = fs.readFileSync(err.loc.file, 'utf-8'); - } catch { - // empty - } - } - err.frame = generateCodeFrame(code, err.loc); - } - } else if ((err as any).line && (err as any).column) { - err.loc = { - file: err.id, - line: (err as any).line, - column: (err as any).column, - }; - err.frame = err.frame || generateCodeFrame(err.id!, err.loc); - } - - if (err.loc && ctx instanceof TransformContext) { - const rawSourceMap = ctx._getCombinedSourcemap(); - if (rawSourceMap) { - const consumer = new SourceMapConsumer(rawSourceMap as any); - const { source, line, column } = consumer.originalPositionFor({ - line: Number(err.loc.line), - column: Number(err.loc.column), - bias: SourceMapConsumer.GREATEST_LOWER_BOUND, - }); - if (source) { - err.loc = { file: source, line, column }; - } - } - } - } - - return err; - } - - class TransformContext extends Context { - filename: string; - originalCode: string; - originalSourcemap: SourceMap | null = null; - sourcemapChain: Array> = []; - combinedMap: SourceMap | null = null; - - constructor(filename: string, code: string, inMap?: SourceMap | string) { - super(); - this.filename = filename; - this.originalCode = code; - if (inMap) { - this.sourcemapChain.push(inMap); - } - } - - _getCombinedSourcemap(createIfNull = false) { - let { combinedMap } = this; - for (let m of this.sourcemapChain) { - if (typeof m === 'string') m = JSON.parse(m); - if (!('version' in (m as SourceMap))) { - // empty, nullified source map - this.combinedMap = null; - combinedMap = this.combinedMap; - this.sourcemapChain.length = 0; - break; - } - if (!combinedMap) { - combinedMap = m as SourceMap; - } else { - combinedMap = combineSourcemaps(this.filename, [ - { - ...(m as RawSourceMap), - sourcesContent: combinedMap.sourcesContent, - }, - combinedMap as RawSourceMap, - ]) as SourceMap; - } - } - if (!combinedMap) { - return createIfNull - ? new MagicString(this.originalCode).generateMap({ - includeContent: true, - hires: true, - source: this.filename, - }) - : null; - } - if (combinedMap !== this.combinedMap) { - this.combinedMap = combinedMap; - this.sourcemapChain.length = 0; - } - return this.combinedMap; - } - - getCombinedSourcemap() { - return this._getCombinedSourcemap(true) as SourceMap; - } - } - - let closed = false; - - const container: PluginContainer = { - options: await (async () => { - let options = rollupOptions; - for (const plugin of plugins) { - if (!plugin.options) continue; - options = (await callHook(plugin.options, minimalContext, options)) || options; - } - // NOTE: maybe unused, try remove it in the future - if ((options as any).acornInjectPlugins) { - parser = acorn.Parser.extend((options as any).acornInjectPlugins as any); - } - return { - acorn, - acornInjectPlugins: [], - ...options, - }; - })(), - - getModuleInfo, - - async buildStart() { - await Promise.all( - plugins.map((plugin) => { - if (plugin.buildStart) { - return callHook(plugin.buildStart, new Context(plugin), container.options as NormalizedInputOptions); - } - return null; - }), - ); - }, - - async resolveId(rawId, importer = join(root, 'index.html'), options) { - const skip = options?.skip; - const ctx = new Context(); - ctx._resolveSkips = skip; - const resolveStart = isDebug ? performance.now() : 0; - - let id: string | null = null; - const partial: Partial = {}; - for (const plugin of plugins) { - if (!plugin.resolveId) continue; - if (skip?.has(plugin)) continue; - - ctx._activePlugin = plugin; - - const pluginResolveStart = isDebug ? performance.now() : 0; - const result = await callHook(plugin.resolveId, ctx, rawId, importer, { - // TODO: mock - attributes: {}, - isEntry: false, - }); - if (!result) continue; - - if (typeof result === 'string') { - id = result; - } else { - id = result.id; - Object.assign(partial, result); - } - - isDebug && - debugPluginResolve( - timeFrom(pluginResolveStart), - plugin.name, - // prettifyUrl(id, root), - ); - - // resolveId() is hookFirst - first non-null result is returned. - break; - } - - if (isDebug && rawId !== id && !rawId.startsWith(FS_PREFIX)) { - const key = rawId + id; - // avoid spamming - if (!seenResolves[key]) { - seenResolves[key] = true; - debugResolve.info(`${timeFrom(resolveStart)}`, `${colors.cyan(rawId)} -> ${colors.dim(id)}`); - } - } - - if (id) { - partial.id = isExternalUrl(id) ? id : normalizePath(id); - return partial as PartialResolvedId; - } else { - return null; - } - }, - - async load(id, options) { - const ssr = options?.ssr; - const ctx = new Context(); - ctx.ssr = !!ssr; - for (const plugin of plugins) { - if (!plugin.load) continue; - ctx._activePlugin = plugin; - - const result = await callHook(plugin.load, ctx, id); - if (result != null) { - if (isObject(result)) { - updateModuleInfo(id, result); - } - return result; - } - } - return null; - }, - - async transform(code, id, options) { - const inMap = options?.inMap; - const ctx = new TransformContext(id, code, inMap as SourceMap); - let meta = null; - for (const plugin of plugins) { - if (!plugin.transform) continue; - ctx._activePlugin = plugin; - ctx._activeId = id; - ctx._activeCode = code; - const start = isDebug ? performance.now() : 0; - let result: TransformResult | string | undefined; - try { - result = await callHook(plugin.transform, ctx, code, id); - } catch (e) { - ctx.error(e as any); - } - if (!result) continue; - isDebug && - debugPluginTransform( - timeFrom(start), - plugin.name, - // prettifyUrl(id, root), - ); - if (isObject(result)) { - if (result.code !== undefined) { - code = result.code; - if (result.map) { - ctx.sourcemapChain.push(result.map); - } - - // Add to support custom meta info - if (result.meta) { - meta = result.meta; - } - } - updateModuleInfo(id, result); - } else { - code = result; - } - } - return { - code, - map: ctx._getCombinedSourcemap(), - meta, - }; - }, - - async close() { - if (closed) return; - const ctx = new Context(); - await Promise.all(plugins.map((p) => p.buildEnd && callHook(p.buildEnd, ctx))); - await Promise.all(plugins.map((p) => p.closeBundle && callHook(p.closeBundle, ctx))); - closed = true; - }, - }; - - return container; -} - -async function callHook any>( - hook: ObjectHook, - ctx: any, - ...args: Parameters -): Promise>> { - if (typeof hook === 'function') { - return await hook.call(ctx, ...args); - } - // ignore hook order - return await hook.handler.call(ctx, ...args); -} diff --git a/packages/pkg/src/rollupPlugins/swc.ts b/packages/pkg/src/rollupPlugins/swc.ts index 7943970c..281bacda 100644 --- a/packages/pkg/src/rollupPlugins/swc.ts +++ b/packages/pkg/src/rollupPlugins/swc.ts @@ -1,4 +1,4 @@ -import { extname, basename, relative, sep } from 'path'; +import { extname, relative, sep } from 'path'; import * as swc from '@swc/core'; import { isTypescriptOnly } from '../helpers/suffix.js'; import { @@ -95,9 +95,6 @@ const swcPlugin = ( absolutePath: id, ext: extname(id), }; - // If file's name comes with .mjs、.mts、.cjs、.cts suffix - const destExtname = ['m', 'c'].includes(file.ext[1]) ? `.${file.ext[1]}js` : '.js'; - const destFilename = basename(id).replace(RegExp(`${extname(id)}$`), destExtname); const sourceFileName = `.${sep}${relative(rootDir, id)}`; const { code, map } = await swc.transform( @@ -115,9 +112,6 @@ const swcPlugin = ( return { code: code, map: map, - meta: { - filename: destFilename, - }, }; }, options(options) { diff --git a/packages/pkg/src/tasks/transform.ts b/packages/pkg/src/tasks/transform.ts index b8c48527..60254135 100644 --- a/packages/pkg/src/tasks/transform.ts +++ b/packages/pkg/src/tasks/transform.ts @@ -1,17 +1,18 @@ import { performance } from 'perf_hooks'; -import { isAbsolute, resolve, extname, dirname, relative, basename } from 'path'; +import { isAbsolute, resolve, extname, relative, dirname } from 'path'; import fs from 'fs-extra'; import semverGtr from 'semver/ranges/gtr.js'; import { consola } from 'consola'; -import { loadEntryFiles, loadSource, INCLUDES_UTF8_FILE_TYPE } from '../helpers/load.js'; -import { createPluginContainer } from '../helpers/pluginContainer.js'; -import { checkDependencyExists, isObject, RequireKeys, timeFrom } from '../utils.js'; +import { createFilter } from '@rollup/pluginutils'; +import { loadEntryFiles } from '../helpers/load.js'; +import { checkDependencyExists, createScriptsFilter, timeFrom, toArray, unique } from '../utils.js'; import type { OutputFile, OutputResult, TaskRunnerContext, TransformTaskConfig, WatchChangedFile } from '../types.js'; -import { SourceDescription, type Plugin, type RollupOptions, type SourceMapInput } from 'rollup'; -import { getTransformEntryDirs } from '../helpers/getTaskIO.js'; +import { rollup, type ExternalOption, type OutputOptions, type Plugin, type RollupOptions } from 'rollup'; +import { getTransformEntryDirs, getTransformEntryRoot } from '../helpers/getTaskIO.js'; import { getRollupOptions } from '../engine/rollup/options.js'; +import { toOutputFiles } from '../engine/rollup/output.js'; +import { withFilteredRollupWarnings } from '../engine/rollup/warn.js'; import { Runner } from '../helpers/runner.js'; -import { getExistedChangedFilesPath } from '../helpers/watcher.js'; export function createTransformTask(taskRunnerContext: TaskRunnerContext) { return new TransformRunner(taskRunnerContext); @@ -19,169 +20,161 @@ export function createTransformTask(taskRunnerContext: TaskRunnerContext) { class TransformRunner extends Runner { private rollupOptions: RollupOptions; + private cache: { + allEntryDirs: string[]; + entryRoot: string; + excludes: string | string[]; + scriptFilter: ReturnType; + isEntryFileIncluded: (filePath: string) => boolean; + }; constructor(taskRunnerContext: TaskRunnerContext) { super(taskRunnerContext); + const { buildContext, buildTask } = taskRunnerContext; + const { rootDir } = buildContext; + const config = buildTask.config as TransformTaskConfig; + const entry = config.entry as Record; + const allEntryDirs = getTransformEntryDirs(rootDir, entry); + const entryRoot = config.entryRoot ?? getTransformEntryRoot(rootDir, entry); + const excludes = config.excludes ?? []; + + this.cache = { + allEntryDirs, + entryRoot, + excludes, + scriptFilter: createScriptsFilter(), + isEntryFileIncluded: createEntryFileIncludeMatcher(excludes), + }; this.rollupOptions = getRollupOptions(taskRunnerContext.buildContext, taskRunnerContext); + if (taskRunnerContext.watcher) { - const entryDirs = getTransformEntryDirs( - taskRunnerContext.buildContext.rootDir, - taskRunnerContext.buildTask.config.entry as Record, - ); - taskRunnerContext.watcher.add(entryDirs); + taskRunnerContext.watcher.add(this.cache.allEntryDirs); } } override doRun(files?: WatchChangedFile[]): Promise { - return runTransform(this, this.rollupOptions, files ? getExistedChangedFilesPath(files) : undefined); + return runTransform(this, this.rollupOptions, files); + } + + getCache() { + return this.cache; } } -type TransformOutputFile = RequireKeys; +interface ResolvedCollectedFile extends CollectedFile { + dest: string; + filename: string; +} + +interface CollectedFile { + filePath: string; + absolutePath: string; + ext: string; +} + +function createEntryFileIncludeMatcher(excludes: string | string[]) { + const patterns = ['node_modules/**', ...toArray(excludes ?? [])]; + const filter = createFilter(undefined, patterns); + return (filePath: string) => { + const normalizedFilePath = filePath.split('\\').join('/'); + return filter(normalizedFilePath); + }; +} async function runTransform( - task: Runner, + task: TransformRunner, rollupOptions: RollupOptions, - updatedFiles?: string[], + changedFiles?: WatchChangedFile[], ): Promise { const taskRunnerContext = task.context; const { logger } = task; - const { buildContext } = taskRunnerContext; let isDistContainingSWCHelpers = false; let isDistContainingJSXRuntime = false; - const { rootDir, userConfig } = buildContext; const { buildTask } = taskRunnerContext; const { name: taskName } = buildTask; const config = buildTask.config as TransformTaskConfig; + const { allEntryDirs, entryRoot, excludes, scriptFilter, isEntryFileIncluded } = task.getCache(); - const entryDirs = getTransformEntryDirs(rootDir, config.entry as Record); - - if (config.sourcemap === 'inline') { - task.logger.warn('The sourcemap "inline" for transform has not fully supported.'); - } - - const files: TransformOutputFile[] = []; + const entryDirs = getTargetEntryDirs(allEntryDirs, changedFiles); - if (updatedFiles) { - for (const updatedFile of updatedFiles) { - for (const entryDir of entryDirs) { - if (updatedFile.startsWith(entryDir)) { - files.push(getFileInfo(updatedFile, entryDir)); - break; - } - } - } - } else { - for (const entryDir of entryDirs) { - files.push( - ...loadEntryFiles(entryDir, userConfig?.transform?.excludes || []).map((filePath) => ({ - filePath, - absolutePath: resolve(entryDir, filePath), - ext: extname(filePath), - })), - ); - } + if (changedFiles?.length) { + logger.debug( + `Rebuild transform task (${taskName}) for ${changedFiles.length} changed files and ${entryDirs.length} entry dirs.`, + ); } - const container = await createPluginContainer({ - // asset plugins is Plugin[] - plugins: rollupOptions.plugins as Plugin[], - root: rootDir, - output: config.outputDir!, - logger, - build: { - rollupOptions, - }, + const files = shouldFullRebuild(changedFiles) + ? collectTransformFiles(entryDirs, excludes, entryRoot) + : collectChangedTransformFiles(entryDirs, changedFiles ?? [], entryRoot, isEntryFileIncluded); + const resolvedFiles = files.map((file) => { + const dest = resolve(config.outputDir!, file.filePath); + return { + ...file, + dest, + filename: relative(config.outputDir!, dest), + }; }); - // @ts-expect-error FIXME: config type. - await container.buildStart(config); - task.updateProgress(0, files.length); - - for (let i = 0; i < files.length; ++i) { - const traverseFileStart = performance.now(); - // those are required keys - const file = files[i] as RequireKeys; - const { absolutePath, filePath } = file; - const dest = resolve(config.outputDir!, filePath); - file.dest = dest; - - await fs.ensureDir(dirname(dest)); - - const resolved = await container.resolveId(filePath, absolutePath); - const id = resolved?.id ?? absolutePath; + await removeDeletedOutputs(config, entryDirs, changedFiles, entryRoot); - const loadResult = await container.load(id); + const rollupInputs = unique(files.filter((file) => scriptFilter(file.absolutePath)).map((file) => file.absolutePath)); + const emittedFileSet = new Set(); + const outputFiles: OutputFile[] = []; - let code = ''; - let map: SourceMapInput | undefined = undefined; + task.updateProgress(0, resolvedFiles.length); - // User should use plugins to transform other types of files. - if (loadResult === null && !INCLUDES_UTF8_FILE_TYPE.test(file.ext)) { - await fs.copyFile(absolutePath, dest); + if (rollupInputs.length) { + const buildStart = performance.now(); + const bundle = await rollup({ + ...withFilteredRollupWarnings(rollupOptions), + input: rollupInputs, + external: rollupOptions.external ?? defaultTransformExternal, + plugins: [transformRelativeExternalPlugin(), ...((rollupOptions.plugins as Plugin[]) ?? [])], + }); - logger.debug(`Transform file ${absolutePath}`, timeFrom(traverseFileStart)); - logger.debug(`Copy File ${absolutePath} to ${dest}`); - - continue; - } + const output = await bundle.write(getTransformOutputOptions(config, entryRoot)); + await bundle.close(); - if (loadResult === null) { - code = await loadSource(absolutePath); - // Need to generate .map ? - } else if (isObject(loadResult)) { - code = loadResult.code; - map = loadResult.map; + for (const item of output.output) { + emittedFileSet.add(resolve(config.outputDir!, item.fileName)); } - const transformResult = await container.transform(code, absolutePath); + outputFiles.push(...toOutputFiles(output.output, config.outputDir!)); - if (transformResult === null || (isObject(transformResult) && transformResult.code == null)) { - // Do not need to transform the code. - } else if (isObject(transformResult)) { - const resultCode = transformResult.code as string | undefined; - if (typeof resultCode === 'string') { - file.code = code = resultCode; + for (const item of output.output) { + if (item.type !== 'chunk') { + continue; } - const resultMap = transformResult.map as SourceMapInput | undefined; - if (resultMap != null) { - file.map = map = resultMap as SourceMapInput; - } - - const destFilename = transformResult?.meta?.filename; - if (destFilename) { - file.dest = file.dest.replace(basename(file.dest), destFilename); + if (!isDistContainingSWCHelpers) { + isDistContainingSWCHelpers = item.code.includes('@swc/helpers'); + } + if (!isDistContainingJSXRuntime) { + isDistContainingJSXRuntime = item.code.includes('@ice/jsx-runtime'); } } - // IMPROVE: should disable sourcemap generation in the transform step for speed. - if (map && config.sourcemap !== false) { - const standardizedMap = typeof map === 'string' ? map : JSON.stringify(map); - const filenameForMap = transformResult?.meta?.filename - ? `${transformResult.meta.filename}.map` - : `${basename(file.dest)}.map`; - const destPath = file.dest; - await fs.writeFile(destPath, `${code}\n //# sourceMappingURL=${filenameForMap}`, 'utf-8'); - await fs.writeFile(`${destPath}.map`, standardizedMap, 'utf-8'); - } else { - await fs.writeFile(file.dest, code, 'utf-8'); - } + logger.debug(`Rollup preserveModules (${rollupInputs.length} inputs)`, timeFrom(buildStart)); + } - if (!isDistContainingSWCHelpers) { - isDistContainingSWCHelpers = !!code && code.includes('@swc/helpers'); - } - if (!isDistContainingJSXRuntime) { - isDistContainingJSXRuntime = !!code && code.includes('@ice/jsx-runtime'); + for (const file of resolvedFiles) { + const traverseFileStart = performance.now(); + if (scriptFilter(file.absolutePath) || emittedFileSet.has(file.dest)) { + task.updateProgress(1); + continue; } - logger.debug(`Transform file ${absolutePath}`, timeFrom(traverseFileStart)); + await fs.ensureDir(dirname(file.dest)); + await fs.copyFile(file.absolutePath, file.dest); + emittedFileSet.add(file.dest); + outputFiles.push(file); + + logger.debug(`Copy file ${file.absolutePath} to ${file.dest}`); + logger.debug(`Transform file ${file.absolutePath}`, timeFrom(traverseFileStart)); task.updateProgress(1); } - await container.close(); - if (isDistContainingSWCHelpers) { // take the semver in package.json for now, the actual used version may not be the same const curUsedRange = checkDependencyExists('@swc/helpers', 'https://pkg.ice.work/faq'); @@ -201,16 +194,178 @@ async function runTransform( } return { - outputFiles: files.map((file) => ({ ...file, filename: relative(config.outputDir!, file.dest!) })), + outputFiles, taskName, }; } -function getFileInfo(filePath: string, rootDir: string): TransformOutputFile { - const relativeFilePath = isAbsolute(filePath) ? relative(rootDir, filePath) : filePath; +function collectTransformFiles(entryDirs: string[], excludes: string | string[], entryRoot: string): CollectedFile[] { + const files: CollectedFile[] = []; + const visited = new Set(); + + for (const entryDir of entryDirs) { + const matchedFiles = loadEntryFiles(entryDir, excludes); + for (const matchedFile of matchedFiles) { + const file = getFileInfo(resolve(entryDir, matchedFile), entryRoot); + if (visited.has(file.absolutePath)) { + continue; + } + visited.add(file.absolutePath); + files.push(file); + } + } + + return files; +} + +export function collectChangedTransformFiles( + entryDirs: string[], + changedFiles: WatchChangedFile[], + entryRoot: string, + isEntryFileIncluded: (filePath: string) => boolean, +): CollectedFile[] { + const files: CollectedFile[] = []; + const visited = new Set(); + + for (const changedFile of changedFiles) { + if (changedFile.event === 'delete') { + continue; + } + + const absolutePath = resolve(changedFile.path); + const entryDir = entryDirs.find((candidate) => isPathInDir(absolutePath, candidate)); + + if (!entryDir) { + continue; + } + + const entryRelativePath = relative(entryDir, absolutePath); + const file = getFileInfo(absolutePath, entryRoot); + + if (!isEntryFileIncluded(entryRelativePath) || visited.has(file.absolutePath)) { + continue; + } + + visited.add(file.absolutePath); + files.push(file); + } + + return files; +} + +function shouldFullRebuild(changedFiles?: WatchChangedFile[]) { + return !changedFiles?.length || changedFiles.some((file) => file.event === 'delete'); +} + +export function getTargetEntryDirs(entryDirs: string[], changedFiles?: WatchChangedFile[]) { + if (!changedFiles?.length) { + return entryDirs; + } + + const changedPaths = changedFiles.map((file) => resolve(file.path)); + const targetEntryDirs = entryDirs.filter((entryDir) => + changedPaths.some((changedPath) => isPathInDir(changedPath, entryDir)), + ); + + return targetEntryDirs.length ? targetEntryDirs : entryDirs; +} + +async function removeDeletedOutputs( + config: TransformTaskConfig, + entryDirs: string[], + changedFiles?: WatchChangedFile[], + entryRoot?: string, +) { + if (!changedFiles?.length) { + return; + } + + const deletedFiles = changedFiles.filter((file) => file.event === 'delete'); + + await Promise.all( + deletedFiles.map(async (file) => { + const absolutePath = resolve(file.path); + const entryDir = entryDirs.find((candidate) => isPathInDir(absolutePath, candidate)); + + if (!entryDir) { + return; + } + + const fileInfo = getFileInfo(absolutePath, entryRoot ?? entryDir); + const directDest = resolve(config.outputDir!, fileInfo.filePath); + const emittedDest = resolve(config.outputDir!, getEmittedFileName(fileInfo.filePath)); + + await fs.remove(directDest); + if (emittedDest !== directDest) { + await fs.remove(emittedDest); + } + + if (config.sourcemap !== false) { + await fs.remove(`${emittedDest}.map`); + } + }), + ); +} + +function isPathInDir(filePath: string, dirPath: string) { + const normalizedFilePath = resolve(filePath); + const normalizedDirPath = resolve(dirPath); + return normalizedFilePath === normalizedDirPath || normalizedFilePath.startsWith(`${normalizedDirPath}/`); +} + +function getTransformOutputOptions(config: TransformTaskConfig, entryRoot: string): OutputOptions { + return { + dir: config.outputDir, + format: config.format.module === 'cjs' ? 'cjs' : 'es', + sourcemap: config.sourcemap, + preserveModules: true, + preserveModulesRoot: entryRoot, + exports: 'auto', + entryFileNames: (chunkInfo) => getChunkFileName(chunkInfo.facadeModuleId, entryRoot), + chunkFileNames: (chunkInfo) => getChunkFileName(chunkInfo.facadeModuleId, entryRoot), + }; +} + +function getChunkFileName(facadeModuleId: string | null, entryDir: string) { + if (!facadeModuleId) { + return '[name].js'; + } + + const relativePath = relative(entryDir, facadeModuleId); + return getEmittedFileName(relativePath); +} + +function getEmittedFileName(relativePath: string) { + const ext = extname(relativePath); + const destExt = ext === '.cts' || ext === '.cjs' ? '.cjs' : ext === '.mts' || ext === '.mjs' ? '.mjs' : '.js'; + return relativePath.replace(new RegExp(`${ext}$`), destExt); +} + +const defaultTransformExternal: ExternalOption = (id) => { + return !id.startsWith('.') && !isAbsolute(id) && !id.startsWith('\0'); +}; + +function transformRelativeExternalPlugin(): Plugin { + return { + name: 'ice-pkg:transform-relative-external', + resolveId(source, importer) { + if (importer && source.startsWith('.')) { + return { + id: source, + external: true, + }; + } + return null; + }, + }; +} + +function getFileInfo(filePath: string, rootDir: string): CollectedFile { + const absolutePath = isAbsolute(filePath) ? filePath : resolve(rootDir, filePath); + const relativeFilePath = relative(rootDir, absolutePath); return { filePath: relativeFilePath, - absolutePath: resolve(rootDir, relativeFilePath), + absolutePath, ext: extname(relativeFilePath), }; } diff --git a/packages/pkg/src/types.ts b/packages/pkg/src/types.ts index b95de94d..6fd69412 100644 --- a/packages/pkg/src/types.ts +++ b/packages/pkg/src/types.ts @@ -76,6 +76,12 @@ export interface TransformUserConfig { * @see https://github.com/isaacs/minimatch */ excludes?: string | string[]; + + /** + * Root directory used to map transform output paths. + * This only affects output path layout, not file include scope. + */ + entryRoot?: string; } export interface BundleUserConfig { @@ -215,6 +221,12 @@ export interface PkgUserConfig */ outputDir?: string; + /** + * Root directory used to map transform output paths for this pkg. + * Has higher priority than `transform.entryRoot`. + */ + entryRoot?: string; + /** * Disable this pkg to build */ @@ -442,6 +454,11 @@ export interface TransformTaskConfig extends _TaskConfig, Omit; + + /** + * Absolute root directory used to map output paths in transform mode. + */ + entryRoot?: string; } export interface DeclarationTaskConfig extends _TaskConfig, DeclarationUserConfig { diff --git a/packages/pkg/tests/core/init.test.ts b/packages/pkg/tests/core/init.test.ts index 562eff79..379e376a 100644 --- a/packages/pkg/tests/core/init.test.ts +++ b/packages/pkg/tests/core/init.test.ts @@ -289,6 +289,87 @@ describe('initTask', () => { }); describe('transform', () => { + describe('excludes', () => { + it('uses transform.excludes from userConfig', () => { + const task = initTask( + tt('esm', 'esm:es5', { + entry: './src/a/index.ts', + }), + c({ + transform: { + excludes: ['docs/**'], + }, + }), + ); + expect((task.config as TransformTaskConfig).excludes).toEqual(['docs/**']); + }); + + it('taskConfig excludes has highest priority', () => { + const task = initTask( + tt('esm', 'esm:es5', { + entry: './src/a/index.ts', + excludes: ['generated/**'], + }), + c({ + transform: { + excludes: ['docs/**'], + }, + }), + ); + expect((task.config as TransformTaskConfig).excludes).toEqual(['generated/**']); + }); + }); + + describe('entryRoot', () => { + it('uses auto inferred root by default', () => { + const task = initTask( + tt('esm', 'esm:es5', { + entry: { + a: './src/a/index.ts', + b: './src/b/index.ts', + }, + }), + c({}), + ); + expect((task.config as TransformTaskConfig).entryRoot).toEqual(join(MOCK_ROOT, 'src')); + }); + + it('uses transform.entryRoot from userConfig', () => { + const task = initTask( + tt('esm', 'esm:es5', { + entry: './src/a/index.ts', + }), + c({ + transform: { + entryRoot: './src', + }, + }), + ); + expect((task.config as TransformTaskConfig).entryRoot).toEqual(join(MOCK_ROOT, 'src')); + }); + + it('pkg.entryRoot overrides transform.entryRoot', () => { + const task = initTask( + tt('esm', 'esm:es5', { + entry: './src/a/index.ts', + pkg: { + id: 'test-pkg', + module: 'esm', + target: 'es5', + pluginInfos: [], + entryRoot: './src/a', + }, + }), + c({ + transform: { + entryRoot: './src', + }, + }), + ); + expect((task.config as TransformTaskConfig).entryRoot).toEqual(join(MOCK_ROOT, 'src/a')); + }); + }); + describe('modes', () => { it('default is based on command', () => { for (const [newCommand, expected] of [ diff --git a/packages/pkg/tests/helpers/getTaskIO.test.ts b/packages/pkg/tests/helpers/getTaskIO.test.ts new file mode 100644 index 00000000..c91e3186 --- /dev/null +++ b/packages/pkg/tests/helpers/getTaskIO.test.ts @@ -0,0 +1,65 @@ +import { test, expect } from 'vitest'; +import { formatEntry, getCommonAncestorDir, getTransformEntryRoot } from '../../src/helpers/getTaskIO.js'; + +test('formatEntry', () => { + expect(formatEntry('src/index')).toEqual({ + index: 'src/index', + }); + + expect(formatEntry(['src/index', 'src/client'])).toEqual({ + index: 'src/index', + client: 'src/client', + }); + + expect( + formatEntry({ + index: 'src/index', + client: 'src/client', + }), + ).toEqual({ + index: 'src/index', + client: 'src/client', + }); +}); + +test('getCommonAncestorDir', () => { + expect(getCommonAncestorDir(['/root/src/a', '/root/src/b'])).toEqual('/root/src'); + expect(getCommonAncestorDir(['/root/src/a'])).toEqual('/root/src/a'); + expect(getCommonAncestorDir(['/root/src/a/b/c', '/root/src/a/b/d/e'])).toEqual('/root/src/a/b'); + expect(getCommonAncestorDir(['/root/src/a/b/c', '/root/src/x/y'])).toEqual('/root/src'); + expect(getCommonAncestorDir([])).toEqual(''); +}); + +test('getTransformEntryRoot', () => { + const entry = { + a: './src/a/index.ts', + b: './src/b/index.ts', + }; + + expect(getTransformEntryRoot('/root', entry)).toEqual('/root/src'); + expect(getTransformEntryRoot('/root', entry, './src')).toEqual('/root/src'); + expect(getTransformEntryRoot('/root', entry, '/root/src')).toEqual('/root/src'); + expect(() => getTransformEntryRoot('/root', entry, './src/a')).toThrowError(/Invalid entryRoot/); +}); + +test('getTransformEntryRoot with nested entries', () => { + const entry = { + one: './src/features/user/index.ts', + two: './src/features/order/internal/main.ts', + three: './src/features/user/profile/detail.ts', + }; + + expect(getTransformEntryRoot('/root', entry)).toEqual('/root/src/features'); + expect(getTransformEntryRoot('/root', entry, './src/features')).toEqual('/root/src/features'); + expect(getTransformEntryRoot('/root', entry, './src')).toEqual('/root/src'); + expect(() => getTransformEntryRoot('/root', entry, './src/features/user')).toThrowError(/Invalid entryRoot/); +}); + +test('getTransformEntryRoot with single deeply nested entry', () => { + const entry = { + one: './src/components/button/variants/primary/index.ts', + }; + + expect(getTransformEntryRoot('/root', entry)).toEqual('/root/src/components/button/variants/primary'); + expect(getTransformEntryRoot('/root', entry, './src/components')).toEqual('/root/src/components'); +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index a96719b5..838e8f82 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -697,6 +697,12 @@ importers: specifier: ^18.0.0 version: 18.0.15 + tests/integration/transform: + dependencies: + '@ice/pkg': + specifier: workspace:* + version: link:../../../packages/pkg + website: dependencies: '@docusaurus/core': diff --git a/tests/helpers/watch.ts b/tests/helpers/watch.ts new file mode 100644 index 00000000..b8536906 --- /dev/null +++ b/tests/helpers/watch.ts @@ -0,0 +1,208 @@ +import { once } from 'node:events'; +import { spawn, type ChildProcessWithoutNullStreams } from 'node:child_process'; +import path from 'node:path'; +import fs from 'fs-extra'; +import { onTestFinished } from 'vitest'; + +export interface WatchHandle { + child: ChildProcessWithoutNullStreams; + getLogs: () => string; + stop: (options?: { timeout?: number; restore?: boolean }) => Promise; + restore: () => Promise; + waitFor: ( + predicate: () => Promise, + errorMessage: string, + timeout?: number, + interval?: number, + ) => Promise; + waitForFile: (filePath: string, timeout?: number) => Promise; + waitForMissing: (filePath: string, timeout?: number) => Promise; + waitForContent: (filePath: string, content: string, timeout?: number) => Promise; + assertAlive: () => void; + readFile: (filePath: string) => Promise; + writeFile: (filePath: string, content: string) => Promise; + remove: (filePath: string) => Promise; + pathExists: (filePath: string) => Promise; +} + +interface StartWatchOptions { + cwd: string; + configPath: string; + args?: string[]; + watchDir?: string | string[]; + autoStopOnTestFinished?: boolean; +} + +export function startWatch({ + cwd, + configPath, + args = [], + watchDir, + autoStopOnTestFinished = true, +}: StartWatchOptions): WatchHandle { + const child = spawn('./node_modules/.bin/ice-pkg', ['start', '--config', configPath, ...args], { + cwd, + stdio: 'pipe', + }); + + const trackedDirs = (Array.isArray(watchDir) ? watchDir : watchDir ? [watchDir] : []) + .map((dir) => path.resolve(cwd, dir)) + .sort((a, b) => b.length - a.length); + + const originalSnapshots = new Map(); + + let logs = ''; + child.stdout.on('data', (chunk) => { + logs += chunk.toString(); + }); + child.stderr.on('data', (chunk) => { + logs += chunk.toString(); + }); + + const getLogs = () => logs; + + const normalizePath = (filePath: string) => path.resolve(filePath); + + const isTrackedPath = (filePath: string) => { + if (!trackedDirs.length) { + return true; + } + + const normalizedPath = normalizePath(filePath); + return trackedDirs.some((dir) => normalizedPath === dir || normalizedPath.startsWith(`${dir}${path.sep}`)); + }; + + const saveOriginalSnapshot = async (filePath: string) => { + const normalizedPath = normalizePath(filePath); + if (!isTrackedPath(normalizedPath) || originalSnapshots.has(normalizedPath)) { + return; + } + + if (await fs.pathExists(normalizedPath)) { + originalSnapshots.set(normalizedPath, { + exists: true, + content: await fs.readFile(normalizedPath, 'utf8'), + }); + return; + } + + originalSnapshots.set(normalizedPath, { + exists: false, + }); + }; + + const assertAlive = () => { + if (child.exitCode != null) { + throw new Error(`Watch process exited early with code ${child.exitCode}\n\n${getLogs()}`); + } + }; + + const waitFor = async ( + predicate: () => Promise, + errorMessage: string, + timeout = 10 * 1000, + interval = 100, + ) => { + const startTime = Date.now(); + + while (Date.now() - startTime < timeout) { + assertAlive(); + if (await predicate()) { + return; + } + await new Promise((resolve) => setTimeout(resolve, interval)); + } + + throw new Error(`${errorMessage}\n\nWatch logs:\n${getLogs()}`); + }; + + const restore = async () => { + const restoreOperations = [...originalSnapshots.entries()].reverse().map(async ([filePath, snapshot]) => { + if (snapshot.exists) { + await fs.ensureDir(path.dirname(filePath)); + await fs.writeFile(filePath, snapshot.content ?? '', 'utf8'); + } else { + await fs.remove(filePath); + } + }); + + await Promise.all(restoreOperations); + originalSnapshots.clear(); + }; + + const stop = async ({ + timeout = 2000, + restore: shouldRestore = true, + }: { timeout?: number; restore?: boolean } = {}) => { + if (child.exitCode != null) { + if (shouldRestore) { + await restore(); + } + return; + } + + child.kill('SIGTERM'); + const result = await Promise.race([ + once(child, 'exit').then(() => 'exited'), + new Promise<'timeout'>((resolve) => setTimeout(() => resolve('timeout'), timeout)), + ]); + + if (result === 'timeout' && child.exitCode == null) { + child.kill('SIGKILL'); + await once(child, 'exit'); + } + + if (shouldRestore) { + await restore(); + } + }; + + const readFile = (filePath: string) => fs.readFile(filePath, 'utf8'); + const writeFile = async (filePath: string, content: string) => { + await saveOriginalSnapshot(filePath); + await fs.writeFile(filePath, content, 'utf8'); + }; + const remove = async (filePath: string) => { + await saveOriginalSnapshot(filePath); + await fs.remove(filePath); + }; + const pathExists = (filePath: string) => fs.pathExists(filePath); + + const waitForFile = async (filePath: string, timeout = 10 * 1000) => { + await waitFor(async () => pathExists(filePath), `Expected file to exist: ${filePath}`, timeout); + }; + + const waitForMissing = async (filePath: string, timeout = 10 * 1000) => { + await waitFor(async () => !(await pathExists(filePath)), `Expected file to be removed: ${filePath}`, timeout); + }; + + const waitForContent = async (filePath: string, content: string, timeout = 10 * 1000) => { + await waitFor( + async () => (await pathExists(filePath)) && (await readFile(filePath)).includes(content), + `Expected file to contain content: ${filePath}`, + timeout, + ); + }; + + if (autoStopOnTestFinished) { + onTestFinished(async () => { + await stop(); + }); + } + + return { + child, + getLogs, + stop, + restore, + waitFor, + waitForFile, + waitForMissing, + waitForContent, + assertAlive, + readFile, + writeFile, + remove, + pathExists, + }; +} diff --git a/tests/integration/alias/__snapshots__/index.test.ts.snap b/tests/integration/alias/__snapshots__/index.test.ts.snap index 06ebbbca..eefc16fc 100644 --- a/tests/integration/alias/__snapshots__/index.test.ts.snap +++ b/tests/integration/alias/__snapshots__/index.test.ts.snap @@ -38,7 +38,8 @@ exports[`Run config default > file content cjs/alias.d.ts 1`] = ` `; exports[`Run config default > file content cjs/alias.js 1`] = ` -""use strict"; +"'use strict'; + Object.defineProperty(exports, "__esModule", { value: true }); @@ -60,7 +61,8 @@ export { bar }; `; exports[`Run config default > file content cjs/index.js 1`] = ` -""use strict"; +"'use strict'; + Object.defineProperty(exports, "__esModule", { value: true }); @@ -89,7 +91,9 @@ exports[`Run config default > file content es2017/alias.d.ts 1`] = ` `; exports[`Run config default > file content es2017/alias.js 1`] = ` -"export const bar = 2; +"const bar = 2; + +export { bar }; " `; @@ -101,9 +105,11 @@ export { bar }; `; exports[`Run config default > file content es2017/index.js 1`] = ` -"import { bar } from './alias.js'; -export const foo = 1; -export { bar }; +"export { bar } from './alias.js'; + +const foo = 1; + +export { foo }; " `; @@ -113,7 +119,9 @@ exports[`Run config default > file content esm/alias.d.ts 1`] = ` `; exports[`Run config default > file content esm/alias.js 1`] = ` -"export var bar = 2; +"var bar = 2; + +export { bar }; " `; @@ -125,8 +133,10 @@ export { bar }; `; exports[`Run config default > file content esm/index.js 1`] = ` -"import { bar } from './alias.js'; -export var foo = 1; -export { bar }; +"export { bar } from './alias.js'; + +var foo = 1; + +export { foo }; " `; diff --git a/tests/integration/default/__snapshots__/index.test.ts.snap b/tests/integration/default/__snapshots__/index.test.ts.snap index e925a478..cf9ed671 100644 --- a/tests/integration/default/__snapshots__/index.test.ts.snap +++ b/tests/integration/default/__snapshots__/index.test.ts.snap @@ -115,7 +115,9 @@ exports[`Run config declaration-generator-oxc > file content es2017/index.d.ts 1 `; exports[`Run config declaration-generator-oxc > file content es2017/index.js 1`] = ` -"export const foo = 1; +"const foo = 1; + +export { foo }; " `; @@ -125,7 +127,9 @@ exports[`Run config declaration-generator-oxc > file content esm/index.d.ts 1`] `; exports[`Run config declaration-generator-oxc > file content esm/index.js 1`] = ` -"export var foo = 1; +"var foo = 1; + +export { foo }; " `; diff --git a/tests/integration/helpers/__snapshots__/index.test.ts.snap b/tests/integration/helpers/__snapshots__/index.test.ts.snap index cea2ba06..3a647477 100644 --- a/tests/integration/helpers/__snapshots__/index.test.ts.snap +++ b/tests/integration/helpers/__snapshots__/index.test.ts.snap @@ -36,14 +36,17 @@ exports[`Run config external-helpers > file content esm/index.d.ts 1`] = ` `; exports[`Run config external-helpers > file content esm/index.js 1`] = ` -"import { _ as _to_consumable_array } from "@swc/helpers/_/_to_consumable_array"; -export function spread(target, sources) { +"import { _ } from '@swc/helpers/_/_to_consumable_array'; + +function spread(target, sources) { var _Object; return (_Object = Object).assign.apply(_Object, [ {}, target - ].concat(_to_consumable_array(sources))); + ].concat(_(sources))); } + +export { spread }; " `; @@ -102,13 +105,15 @@ function _unsupported_iterable_to_array(o, minLen) { if (n === "Map" || n === "Set") return Array.from(n); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen); } -export function spread(target, sources) { +function spread(target, sources) { var _Object; return (_Object = Object).assign.apply(_Object, [ {}, target ].concat(_to_consumable_array(sources))); } + +export { spread }; " `; @@ -132,8 +137,10 @@ exports[`Run config pkg-inline-helpers > file content esm/index.d.ts 1`] = ` `; exports[`Run config pkg-inline-helpers > file content esm/index.js 1`] = ` -"export function spread(target, sources) { +"function spread(target, sources) { return Object.assign({}, target, ...sources); } + +export { spread }; " `; diff --git a/tests/integration/mix-cjs-mjs/__snapshots__/index.test.ts.snap b/tests/integration/mix-cjs-mjs/__snapshots__/index.test.ts.snap index cd86b024..928f6536 100644 --- a/tests/integration/mix-cjs-mjs/__snapshots__/index.test.ts.snap +++ b/tests/integration/mix-cjs-mjs/__snapshots__/index.test.ts.snap @@ -34,7 +34,9 @@ exports[`Run config swc-helpers > esm structure 1`] = ` `; exports[`Run config swc-helpers > file content cjs/cjs.js 1`] = ` -"var _object_spread = require("@swc/helpers/_/_object_spread"); +"'use strict'; + +var _object_spread = require("@swc/helpers/_/_object_spread"); module.exports.add = function(a, b) { return a + b; }; @@ -45,7 +47,9 @@ module.exports.extend = function(a, b) { `; exports[`Run config swc-helpers > file content cjs/cts-file.cjs 1`] = ` -"var _object_spread = require("@swc/helpers/_/_object_spread"); +"'use strict'; + +var _object_spread = require("@swc/helpers/_/_object_spread"); module.exports.ctsFile = function(options) { return _object_spread._({ type: 'ctsFile' @@ -69,7 +73,8 @@ export declare const foo: Record; `; exports[`Run config swc-helpers > file content cjs/entry-mts.js 1`] = ` -""use strict"; +"'use strict'; + Object.defineProperty(exports, "__esModule", { value: true }); @@ -307,16 +312,18 @@ export declare const foo: Record; `; exports[`Run config swc-helpers > file content esm/entry-mts.js 1`] = ` -"import { _ as _object_spread } from "@swc/helpers/_/_object_spread"; -import { add, extend } from './cjs'; -import { ctsFile } from './cts-file.cjs'; -export { add, extend }; -export { ctsFile }; -export var foo = _object_spread({}, extend({ +"import { _ } from '@swc/helpers/_/_object_spread'; +import { extend } from './cjs'; +export { add, extend } from './cjs'; +export { ctsFile } from './cts-file.cjs'; + +var foo = _({}, extend({ a: 1 }, { b: 2 })); + +export { foo }; " `; @@ -354,7 +361,9 @@ exports[`Run config swc-helpers-rolldown > esm structure 1`] = ` `; exports[`Run config swc-helpers-rolldown > file content cjs/cjs.js 1`] = ` -"var _object_spread = require("@swc/helpers/_/_object_spread"); +"'use strict'; + +var _object_spread = require("@swc/helpers/_/_object_spread"); module.exports.add = function(a, b) { return a + b; }; @@ -365,7 +374,9 @@ module.exports.extend = function(a, b) { `; exports[`Run config swc-helpers-rolldown > file content cjs/cts-file.cjs 1`] = ` -"var _object_spread = require("@swc/helpers/_/_object_spread"); +"'use strict'; + +var _object_spread = require("@swc/helpers/_/_object_spread"); module.exports.ctsFile = function(options) { return _object_spread._({ type: 'ctsFile' @@ -389,7 +400,8 @@ export declare const foo: Record; `; exports[`Run config swc-helpers-rolldown > file content cjs/entry-mts.js 1`] = ` -""use strict"; +"'use strict'; + Object.defineProperty(exports, "__esModule", { value: true }); @@ -575,15 +587,17 @@ export declare const foo: Record; `; exports[`Run config swc-helpers-rolldown > file content esm/entry-mts.js 1`] = ` -"import { _ as _object_spread } from "@swc/helpers/_/_object_spread"; -import { add, extend } from './cjs'; -import { ctsFile } from './cts-file.cjs'; -export { add, extend }; -export { ctsFile }; -export var foo = _object_spread({}, extend({ +"import { _ } from '@swc/helpers/_/_object_spread'; +import { extend } from './cjs'; +export { add, extend } from './cjs'; +export { ctsFile } from './cts-file.cjs'; + +var foo = _({}, extend({ a: 1 }, { b: 2 })); + +export { foo }; " `; diff --git a/tests/integration/plugins/__snapshots__/index.test.ts.snap b/tests/integration/plugins/__snapshots__/index.test.ts.snap index 930474ae..28f9201c 100644 --- a/tests/integration/plugins/__snapshots__/index.test.ts.snap +++ b/tests/integration/plugins/__snapshots__/index.test.ts.snap @@ -30,10 +30,12 @@ export declare const info: any; `; exports[`Run config pkg-scope > file content es2017/index.js 1`] = ` -"export const foo = 1; -export const info = { +"const foo = 1; +const info = { "name": "global" }; + +export { foo, info }; " `; @@ -47,10 +49,12 @@ export declare const info: any; `; exports[`Run config pkg-scope > file content esm/index.js 1`] = ` -"export var foo = 1; -export var info = { +"var foo = 1; +var info = { "name": "pkg-config" }; + +export { foo, info }; " `; @@ -80,10 +84,12 @@ export declare const info: any; `; exports[`Run config plugin-scope > file content es2017/index.js 1`] = ` -"export const foo = 1; -export const info = { +"const foo = 1; +const info = { "pluginScope": "global" }; + +export { foo, info }; " `; @@ -97,10 +103,12 @@ export declare const info: any; `; exports[`Run config plugin-scope > file content esm/index.js 1`] = ` -"export var foo = 1; -export var info = { +"var foo = 1; +var info = { "pluginScope": "pkg" }; + +export { foo, info }; " `; diff --git a/tests/integration/react/__snapshots__/index.test.ts.snap b/tests/integration/react/__snapshots__/index.test.ts.snap index 819dde2f..207fde1e 100644 --- a/tests/integration/react/__snapshots__/index.test.ts.snap +++ b/tests/integration/react/__snapshots__/index.test.ts.snap @@ -31,18 +31,21 @@ export default _default; `; exports[`Run config default > file content esm/index.js 1`] = ` -"import { _ as _object_spread } from "@swc/helpers/_/_object_spread"; -import { _ as _object_spread_props } from "@swc/helpers/_/_object_spread_props"; -import { jsx as _jsx } from "@ice/jsx-runtime/jsx-runtime"; -import React from 'react'; -export default function() { +"import { _ as _$1 } from '@swc/helpers/_/_object_spread'; +import { _ } from '@swc/helpers/_/_object_spread_props'; +import { jsx } from '@ice/jsx-runtime/jsx-runtime'; +import 'react'; + +function index() { var commonProps = { className: 'common-class-name' }; - return /*#__PURE__*/ _jsx("div", _object_spread_props(_object_spread({}, commonProps), { + return /*#__PURE__*/ jsx("div", _(_$1({}, commonProps), { children: "Hello World" })); -}; +} + +export { index as default }; " `; @@ -77,18 +80,21 @@ export default _default; `; exports[`Run config pkg > file content esm/index.js 1`] = ` -"import { _ as _object_spread } from "@swc/helpers/_/_object_spread"; -import { _ as _object_spread_props } from "@swc/helpers/_/_object_spread_props"; -import { jsx as _jsx } from "@ice/jsx-runtime/jsx-runtime"; -import React from 'react'; -export default (()=>{ +"import { _ as _$1 } from '@swc/helpers/_/_object_spread'; +import { _ } from '@swc/helpers/_/_object_spread_props'; +import { jsx } from '@ice/jsx-runtime/jsx-runtime'; +import 'react'; + +var index = (()=>{ const commonProps = { className: 'common-class-name' }; - return /*#__PURE__*/ _jsx("div", _object_spread_props(_object_spread({}, commonProps), { + return /*#__PURE__*/ jsx("div", _(_$1({}, commonProps), { children: "Hello World" })); }); + +export { index as default }; " `; diff --git a/tests/integration/transform/__snapshots__/index.test.ts.snap b/tests/integration/transform/__snapshots__/index.test.ts.snap new file mode 100644 index 00000000..4a97f653 --- /dev/null +++ b/tests/integration/transform/__snapshots__/index.test.ts.snap @@ -0,0 +1,218 @@ +// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html + +exports[`Run config copy-non-script-files > esm structure 1`] = ` +[ + "esm/", + "├── docs/", + "│ └── readme.md", + "├── ext-cjs.cjs", + "├── ext-cts.cjs", + "├── ext-jsx.js", + "├── ext-mjs.mjs", + "├── ext-mts.mjs", + "├── ext-tsx.js", + "├── ext-types.d.ts", + "├── logic.js", + "├── main.js", + "├── meta.yaml", + "├── skip.ignore.txt", + "└── styles/", + " ├── copy.less", + " └── copy.scss", +] +`; + +exports[`Run config copy-non-script-files > file content esm/docs/readme.md 1`] = ` +"# copy fixture + +this markdown file should be copied. +" +`; + +exports[`Run config copy-non-script-files > file content esm/ext-cjs.cjs 1`] = ` +"exports.cjsValue = 'cjs-value'; +" +`; + +exports[`Run config copy-non-script-files > file content esm/ext-cts.cjs 1`] = ` +"Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "ctsValue", { + enumerable: true, + get: function() { + return ctsValue; + } +}); +var ctsValue = 'cts-value'; +" +`; + +exports[`Run config copy-non-script-files > file content esm/ext-jsx.js 1`] = ` +"var jsxValue = 'jsx-value'; + +export { jsxValue }; +" +`; + +exports[`Run config copy-non-script-files > file content esm/ext-mjs.mjs 1`] = ` +"var mjsValue = 'mjs-value'; + +export { mjsValue }; +" +`; + +exports[`Run config copy-non-script-files > file content esm/ext-mts.mjs 1`] = ` +"var mtsValue = 'mts-value'; + +export { mtsValue }; +" +`; + +exports[`Run config copy-non-script-files > file content esm/ext-tsx.js 1`] = ` +"var tsxValue = 'tsx-value'; + +export { tsxValue }; +" +`; + +exports[`Run config copy-non-script-files > file content esm/ext-types.d.ts 1`] = ` +"export interface CopiedType { + value: string; +} +" +`; + +exports[`Run config copy-non-script-files > file content esm/logic.js 1`] = ` +"var title = 'copy-non-script'; + +export { title }; +" +`; + +exports[`Run config copy-non-script-files > file content esm/main.js 1`] = ` +"export { title } from './logic'; +import './styles/copy.less'; +import './styles/copy.scss'; +" +`; + +exports[`Run config copy-non-script-files > file content esm/meta.yaml 1`] = ` +"name: copy-fixture +kind: static +" +`; + +exports[`Run config copy-non-script-files > file content esm/skip.ignore.txt 1`] = ` +"excluded from copy fixture +" +`; + +exports[`Run config copy-non-script-files > file content esm/styles/copy.less 1`] = ` +"@copy-color: #0ea5e9; + +.copy-less { + color: @copy-color; +} +" +`; + +exports[`Run config copy-non-script-files > file content esm/styles/copy.scss 1`] = ` +"$copy-bg: #ecfeff; + +.copy-scss { + background: $copy-bg; +} +" +`; + +exports[`Run config entry-root-wide > esm structure 1`] = ` +[ + "esm/", + "└── src/", + " ├── docs/", + " │ └── readme.md", + " ├── ext-cjs.cjs", + " ├── ext-cts.cjs", + " ├── ext-jsx.js", + " ├── ext-mjs.mjs", + " ├── ext-mts.mjs", + " ├── ext-tsx.js", + " ├── ext-types.d.ts", + " ├── logic.js", + " ├── main.js", + " ├── meta.yaml", + " ├── skip.ignore.txt", + " └── styles/", + " ├── copy.less", + " └── copy.scss", +] +`; + +exports[`Run config excludes > esm structure 1`] = ` +[ + "esm/", + "├── ext-cjs.cjs", + "├── ext-cts.cjs", + "├── ext-jsx.js", + "├── ext-mjs.mjs", + "├── ext-mts.mjs", + "├── ext-tsx.js", + "├── ext-types.d.ts", + "├── logic.js", + "├── main.js", + "├── meta.yaml", + "└── styles/", + " ├── copy.less", + " └── copy.scss", +] +`; + +exports[`Run config multi-entry > esm structure 1`] = ` +[ + "esm/", + "├── src/", + "│ ├── docs/", + "│ │ └── readme.md", + "│ ├── ext-cjs.cjs", + "│ ├── ext-cts.cjs", + "│ ├── ext-jsx.js", + "│ ├── ext-mjs.mjs", + "│ ├── ext-mts.mjs", + "│ ├── ext-tsx.js", + "│ ├── ext-types.d.ts", + "│ ├── logic.js", + "│ ├── main.js", + "│ ├── meta.yaml", + "│ ├── skip.ignore.txt", + "│ └── styles/", + "│ ├── copy.less", + "│ └── copy.scss", + "└── src-multi-right/", + " ├── entry.js", + " └── nested/", + " └── label.js", +] +`; + +exports[`Run config pkg > esm structure 1`] = ` +[ + "esm/", + "├── docs/", + "│ └── readme.md", + "├── ext-cjs.cjs", + "├── ext-cts.cjs", + "├── ext-jsx.js", + "├── ext-mjs.mjs", + "├── ext-mts.mjs", + "├── ext-tsx.js", + "├── ext-types.d.ts", + "├── logic.js", + "├── main.js", + "├── meta.yaml", + "├── skip.ignore.txt", + "└── styles/", + " ├── copy.less", + " └── copy.scss", +] +`; diff --git a/tests/integration/transform/build.config.watch-test.mts b/tests/integration/transform/build.config.watch-test.mts new file mode 100644 index 00000000..22f9640a --- /dev/null +++ b/tests/integration/transform/build.config.watch-test.mts @@ -0,0 +1,14 @@ +import { defineConfig } from '@ice/pkg'; + +export default defineConfig({ + declaration: false, + sourceMaps: false, + entry: { + a: './src/main.ts', + b: './src-multi-right/entry.ts', + }, + transform: { + formats: ['esm'], + excludes: ['**/*.ignore.txt'], + }, +}); \ No newline at end of file diff --git a/tests/integration/transform/index.test.ts b/tests/integration/transform/index.test.ts new file mode 100644 index 00000000..7344ce26 --- /dev/null +++ b/tests/integration/transform/index.test.ts @@ -0,0 +1,149 @@ +import { runProjectTest } from '../../helpers/run'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { expect, test } from 'vitest'; +import { startWatch } from '../../helpers/watch'; +import type { TransformUserFormat } from '../../../packages/pkg/src/types'; + +const projectPath = path.dirname(fileURLToPath(import.meta.url)); + +const baseConfig = { + declaration: false, + sourceMaps: false, + transform: { + formats: ['esm'] as TransformUserFormat[], + }, +}; + +runProjectTest(import.meta.url, [ + { + name: 'copy-non-script-files', + config: { + ...baseConfig, + entry: './src/main.ts', + }, + snapshot: 'full', + snapshotFolders: ['esm'], + }, + { + name: 'multi-entry', + config: { + ...baseConfig, + entry: { + a: './src/main.ts', + b: './src-multi-right/entry.ts', + }, + }, + snapshot: 'structure', + snapshotFolders: ['esm'], + }, + { + name: 'entry-root-wide', + config: { + ...baseConfig, + entry: './src/main.ts', + transform: { + ...baseConfig.transform, + entryRoot: './', + }, + }, + snapshot: 'structure', + snapshotFolders: ['esm'], + }, + { + name: 'excludes', + config: { + ...baseConfig, + entry: './src/main.ts', + transform: { + ...baseConfig.transform, + excludes: ['**/*.ignore.txt', 'docs/**'], + }, + }, + snapshot: 'structure', + snapshotFolders: ['esm'], + }, + { + name: 'pkg', + config: { + declaration: false, + sourceMaps: false, + pkgs: [ + { + id: 'pkg-override', + module: 'esm', + target: 'es5', + entry: './src/main.ts', + entryRoot: './src', + outputDir: 'esm', + }, + ], + }, + snapshot: 'structure', + snapshotFolders: ['esm'], + }, +]); + +test( + 'transform watch handles update create delete incrementally', + { + timeout: 30 * 1000, + }, + async () => { + const outputDir = path.join(projectPath, 'esm'); + const srcMainPath = path.join(projectPath, 'src/main.ts'); + const srcReadmePath = path.join(projectPath, 'src/docs/readme.md'); + const createdSourcePath = path.join(projectPath, 'src/docs/watch-created.txt'); + const createdOutputPath = path.join(outputDir, 'src/docs/watch-created.txt'); + const entryOutputPath = path.join(outputDir, 'src-multi-right/entry.js'); + const labelOutputPath = path.join(outputDir, 'src-multi-right/nested/label.js'); + const mainOutputPath = path.join(outputDir, 'src/main.js'); + const readmeOutputPath = path.join(outputDir, 'src/docs/readme.md'); + + const watch = startWatch({ + cwd: projectPath, + configPath: 'build.config.watch-test.mts', + watchDir: ['src', 'src-multi-right'], + }); + + const originalMain = await watch.readFile(srcMainPath); + await watch.readFile(srcReadmePath); + + await watch.remove(outputDir); + await watch.remove(createdSourcePath); + + // Wait for initial watch build to finish and baseline outputs to appear. + await watch.waitForFile(entryOutputPath); + await watch.waitForFile(labelOutputPath); + await watch.waitForFile(mainOutputPath); + await watch.waitForFile(readmeOutputPath); + + // 1) Update a src script file and assert src-multi-right outputs do not change. + const entryContentBeforeUpdate = await watch.readFile(entryOutputPath); + const labelContentBeforeUpdate = await watch.readFile(labelOutputPath); + + await watch.writeFile(srcMainPath, `${originalMain}\nexport const watchOnlyUpdate = 'watch-update';\n`); + + await watch.waitForContent(mainOutputPath, "watchOnlyUpdate = 'watch-update'"); + + expect(await watch.readFile(entryOutputPath)).toBe(entryContentBeforeUpdate); + expect(await watch.readFile(labelOutputPath)).toBe(labelContentBeforeUpdate); + + // 2) Create a src static file and assert it is copied without touching src-multi-right output. + const entryContentBeforeCreate = await watch.readFile(entryOutputPath); + + await watch.writeFile(createdSourcePath, 'created during watch\n'); + + await watch.waitForFile(createdOutputPath); + expect(await watch.readFile(createdOutputPath)).toBe('created during watch\n'); + expect(await watch.readFile(entryOutputPath)).toBe(entryContentBeforeCreate); + + // 3) Delete a src static file and assert output is removed without touching src-multi-right output. + const entryContentBeforeDelete = await watch.readFile(entryOutputPath); + + await watch.remove(srcReadmePath); + + await watch.waitForMissing(readmeOutputPath); + expect(await watch.readFile(entryOutputPath)).toBe(entryContentBeforeDelete); + }, +); diff --git a/tests/integration/transform/package.json b/tests/integration/transform/package.json new file mode 100644 index 00000000..1519d96b --- /dev/null +++ b/tests/integration/transform/package.json @@ -0,0 +1,8 @@ +{ + "name": "@ice/pkg-tests-transform", + "version": "0.0.0", + "private": true, + "dependencies": { + "@ice/pkg": "workspace:*" + } +} diff --git a/tests/integration/transform/src-multi-right/entry.ts b/tests/integration/transform/src-multi-right/entry.ts new file mode 100644 index 00000000..be93c560 --- /dev/null +++ b/tests/integration/transform/src-multi-right/entry.ts @@ -0,0 +1,3 @@ +import { label } from './nested/label'; + +export const rightValue = label('right'); diff --git a/tests/integration/transform/src-multi-right/nested/label.ts b/tests/integration/transform/src-multi-right/nested/label.ts new file mode 100644 index 00000000..0e299f48 --- /dev/null +++ b/tests/integration/transform/src-multi-right/nested/label.ts @@ -0,0 +1 @@ +export const label = (name: string) => `multi-${name}`; diff --git a/tests/integration/transform/src/docs/readme.md b/tests/integration/transform/src/docs/readme.md new file mode 100644 index 00000000..765459d6 --- /dev/null +++ b/tests/integration/transform/src/docs/readme.md @@ -0,0 +1,3 @@ +# copy fixture + +this markdown file should be copied. diff --git a/tests/integration/transform/src/ext-cjs.cjs b/tests/integration/transform/src/ext-cjs.cjs new file mode 100644 index 00000000..ecc70530 --- /dev/null +++ b/tests/integration/transform/src/ext-cjs.cjs @@ -0,0 +1 @@ +exports.cjsValue = 'cjs-value'; diff --git a/tests/integration/transform/src/ext-cts.cts b/tests/integration/transform/src/ext-cts.cts new file mode 100644 index 00000000..ed4f44d3 --- /dev/null +++ b/tests/integration/transform/src/ext-cts.cts @@ -0,0 +1 @@ +export const ctsValue = 'cts-value'; diff --git a/tests/integration/transform/src/ext-jsx.jsx b/tests/integration/transform/src/ext-jsx.jsx new file mode 100644 index 00000000..c95dd004 --- /dev/null +++ b/tests/integration/transform/src/ext-jsx.jsx @@ -0,0 +1 @@ +export const jsxValue = 'jsx-value'; diff --git a/tests/integration/transform/src/ext-mjs.mjs b/tests/integration/transform/src/ext-mjs.mjs new file mode 100644 index 00000000..c3f68a1e --- /dev/null +++ b/tests/integration/transform/src/ext-mjs.mjs @@ -0,0 +1 @@ +export const mjsValue = 'mjs-value'; diff --git a/tests/integration/transform/src/ext-mts.mts b/tests/integration/transform/src/ext-mts.mts new file mode 100644 index 00000000..2eb874e1 --- /dev/null +++ b/tests/integration/transform/src/ext-mts.mts @@ -0,0 +1 @@ +export const mtsValue = 'mts-value'; diff --git a/tests/integration/transform/src/ext-tsx.tsx b/tests/integration/transform/src/ext-tsx.tsx new file mode 100644 index 00000000..3197c6c9 --- /dev/null +++ b/tests/integration/transform/src/ext-tsx.tsx @@ -0,0 +1 @@ +export const tsxValue = 'tsx-value'; diff --git a/tests/integration/transform/src/ext-types.d.ts b/tests/integration/transform/src/ext-types.d.ts new file mode 100644 index 00000000..e83420ff --- /dev/null +++ b/tests/integration/transform/src/ext-types.d.ts @@ -0,0 +1,3 @@ +export interface CopiedType { + value: string; +} diff --git a/tests/integration/transform/src/logic.ts b/tests/integration/transform/src/logic.ts new file mode 100644 index 00000000..3fcdd2ad --- /dev/null +++ b/tests/integration/transform/src/logic.ts @@ -0,0 +1 @@ +export const title = 'copy-non-script'; diff --git a/tests/integration/transform/src/main.ts b/tests/integration/transform/src/main.ts new file mode 100644 index 00000000..6038c2f0 --- /dev/null +++ b/tests/integration/transform/src/main.ts @@ -0,0 +1,5 @@ +import { title } from './logic'; +import './styles/copy.less'; +import './styles/copy.scss'; + +export { title }; diff --git a/tests/integration/transform/src/meta.yaml b/tests/integration/transform/src/meta.yaml new file mode 100644 index 00000000..1d8d6ebb --- /dev/null +++ b/tests/integration/transform/src/meta.yaml @@ -0,0 +1,2 @@ +name: copy-fixture +kind: static diff --git a/tests/integration/transform/src/skip.ignore.txt b/tests/integration/transform/src/skip.ignore.txt new file mode 100644 index 00000000..f173c1be --- /dev/null +++ b/tests/integration/transform/src/skip.ignore.txt @@ -0,0 +1 @@ +excluded from copy fixture diff --git a/tests/integration/transform/src/styles/copy.less b/tests/integration/transform/src/styles/copy.less new file mode 100644 index 00000000..81280431 --- /dev/null +++ b/tests/integration/transform/src/styles/copy.less @@ -0,0 +1,5 @@ +@copy-color: #0ea5e9; + +.copy-less { + color: @copy-color; +} diff --git a/tests/integration/transform/src/styles/copy.scss b/tests/integration/transform/src/styles/copy.scss new file mode 100644 index 00000000..6d340ea0 --- /dev/null +++ b/tests/integration/transform/src/styles/copy.scss @@ -0,0 +1,5 @@ +$copy-bg: #ecfeff; + +.copy-scss { + background: $copy-bg; +} diff --git a/website/docs/guide/abilities.md b/website/docs/guide/abilities.md index a188f336..a77c6097 100644 --- a/website/docs/guide/abilities.md +++ b/website/docs/guide/abilities.md @@ -16,8 +16,8 @@ Transform 模式即把源文件逐个编译到输出目录,不对依赖做任 ```md src ├── components -| ├── About.jsx -| └── Button.tsx +| ├── About.jsx +| └── Button.tsx ├── index.ts ├── util.js └── index.scss @@ -28,9 +28,9 @@ src ```md esm ├── components -| ├── About.js -| ├── Button.d.ts -| └── Button.js +| ├── About.js +| ├── Button.d.ts +| └── Button.js ├── index.d.ts ├── index.ts ├── util.js @@ -46,6 +46,13 @@ esm Transform 模式下输出的产物具有较好的调试性,并且对 Tree-Shaking 友好。适用于大部分开发 React/Rax 组件或者 Node 模块场景。 +当配置了多个 entry 时,Transform 只会处理 entry 作用域内的文件,不会隐式处理未配置目录。你可以通过 `transform.entryRoot` 控制输出路径的相对根目录。例如,entry 为 `./src/a/b/c/index.ts` 时: + +- `entryRoot: './src/a/b'` 输出 `esm/c/index.js` +- `entryRoot: './src'` 输出 `esm/a/b/c/index.js` + +若使用 `pkgs`,可在具体 pkg 上配置 `entryRoot`,其优先级高于全局 `transform.entryRoot`。 + ### Bundle 模式 Bundle 模式即以入口文件作为起点,递归处理各种模块,最终把相同类型的文件合并成一个构建产物。目前 [Webpack](https://webpack.js.org/)、[Rollup](https://rollupjs.org) 等就是对源码进行打包构建的工具。 @@ -98,9 +105,7 @@ import * as React from 'react'; import './a.css'; export default function Home() { - return ( -
- ) + return
; } ``` @@ -168,8 +173,8 @@ export default () => ( ```diff - .container { -+ .rc-container { - color: red; ++ .rc-container { + color: red; } ``` @@ -180,12 +185,12 @@ export default () => ( ICE PKG 支持额外输出 ES2017 规范的 [Modern 产物](https://web.dev/publish-modern-javascript/)。这份产物在编译时会保留大部分的 JavaScript 语法特性,比如: -+ Class -+ 箭头函数 -+ async/await -+ 解构 -+ spread 运算符 -+ Generator +- Class +- 箭头函数 +- async/await +- 解构 +- spread 运算符 +- Generator 但可以运行在[大部分的现代浏览器版本](https://caniuse.com/async-functions,object-values,object-entries,mdn-javascript_builtins_object_getownpropertydescriptors,pad-start-end,mdn-javascript_grammar_trailing_commas_trailing_commas_in_functions)上(市场份额 > 95%)。当网站不再转译这些语法时,文件的字节数得以大幅减少,从而极大地改善脚本加载性能。 @@ -214,8 +219,8 @@ export default App; 输出 ES2017 产物与 ES5 产物的大小对比: -| 产物 | 大小 | -|-----------| ---- | +| 产物 | 大小 | +| ----------- | ---- | | ES2017 产物 | 1.8k | | ES5 产物 | 3.7k | diff --git a/website/docs/reference/config.md b/website/docs/reference/config.md index 1dcdd9ff..5d95b630 100644 --- a/website/docs/reference/config.md +++ b/website/docs/reference/config.md @@ -15,18 +15,18 @@ export default defineConfig({ 注:ICE PKG 支持的配置文件类型包括: -+ `build.config.mts` -+ `build.config.mjs` -+ `build.config.ts` -+ `build.config.js` -+ `build.json` +- `build.config.mts` +- `build.config.mjs` +- `build.config.ts` +- `build.config.js` +- `build.json` ## 完整配置项 ### entry -+ 类型:`string | string[] | { [entryAlias: string]: string }` -+ 默认值:`'./src/index'` +- 类型:`string | string[] | { [entryAlias: string]: string }` +- 默认值:`'./src/index'` 指定构建入口。支持配置单入口或者多个入口。 @@ -51,15 +51,15 @@ export default defineConfig({ // 对象形式,key 值作为 chunk name entry: { foo: './src/foo', - bar2: './src/bar' - } + bar2: './src/bar', + }, }); ``` ### alias -+ 类型:`Record` -+ 默认值:`{}` +- 类型:`Record` +- 默认值:`{}` 比如,将 `@` 指向 `./src` 目录。 @@ -77,8 +77,8 @@ export default defineConfig({ ### define -+ 类型:`Record` -+ 默认值:`{ __DEV__: 'true' | 'false', 'process.env.NODE_ENV': '"development"' | '"production"' }` +- 类型:`Record` +- 默认值:`{ __DEV__: 'true' | 'false', 'process.env.NODE_ENV': '"development"' | '"production"' }` 定义编译时环境变量,会在编译时被替换。注意:属性值会经过一次 `JSON.stringify()` 转换。 @@ -90,7 +90,7 @@ import { defineConfig } from '@ice/pkg'; export default defineConfig({ define: { - '__VERSION__': pkg.version, + __VERSION__: pkg.version, }, }); ``` @@ -102,8 +102,9 @@ export default defineConfig({ 在 TS 项目中,需要在 `typings.d.ts` 或其他类型声明文件中,声明 `define` 所设置的属性,以便通过类型检查,并获得类型提示。比如: ```ts title=typings.d.ts -declare const __VERSION__: string +declare const __VERSION__: string; ``` + ::: ICE PKG 默认注入了 `__DEV__` 全局变量,用于标识开发态环境。这个变量在输出一些仅在 development 环境的信息时非常有用。比如,输出在用户开发态才显示的警告信息。 @@ -120,8 +121,8 @@ if (__DEV__) { ### sourceMaps -+ 类型:`boolean | 'inline'` -+ 默认值:start 阶段默认为 `true`,build 阶段默认为 `false` +- 类型:`boolean | 'inline'` +- 默认值:start 阶段默认为 `true`,build 阶段默认为 `false` 是否生成 sourcemap,这在代码调试的时候非常有用。 @@ -145,8 +146,8 @@ export default defineConfig({ ### jsxRuntime -+ 类型:`'automatic' | 'classic'` -+ 默认值:`'automatic'` +- 类型:`'automatic' | 'classic'` +- 默认值:`'automatic'` 设置 [JSX 转换](https://reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html)的方式,并交给编译工具(SWC)编译处理 JSX 语法。 @@ -163,7 +164,7 @@ function App() { 当 `jsxRuntime` 的值是 `automatic`,编译结果是: ```js -import {jsx as _jsx} from 'react/jsx-runtime'; +import { jsx as _jsx } from 'react/jsx-runtime'; function App() { return _jsx('h1', { children: 'Hello world' }); @@ -182,8 +183,8 @@ function App() { ### generateTypesForJs -+ 类型:`boolean` -+ 默认值:`false` +- 类型:`boolean` +- 默认值:`false` 为 JavaScript 代码生成类型文件。ICE PKG 默认为文件后缀为 `.ts` 生成类型文件。 @@ -191,8 +192,8 @@ function App() { ### plugins -+ 类型:`Array` -+ 默认值:`[]` +- 类型:`Array` +- 默认值:`[]` ICE PKG 基于 [build-scripts](https://github.com/ice-lab/build-scripts) 插件系统,配置额外的 ICE PKG 插件,以进行更深度的工程定制。更多内容请参考[插件开发](./plugins-development)。 @@ -206,7 +207,7 @@ export default defineConfig({ // 相对路径 './customPlugin.mjs', // 指定插件选项 - ['@ice/plugin-docusaurus', { title: 'Hello World' }] + ['@ice/plugin-docusaurus', { title: 'Hello World' }], ], }); ``` @@ -224,15 +225,15 @@ import { defineConfig } from '@ice/pkg'; export default defineConfig({ transform: { - formats: ['esm', 'es2017'] - } + formats: ['esm', 'es2017'], + }, }); ``` #### formats -+ 类型:`Array<'cjs' | 'esm' | 'es2017'>` -+ 默认值:`['esm', 'es2017']` +- 类型:`Array<'cjs' | 'esm' | 'es2017'>` +- 默认值:`['esm', 'es2017']` 输出的类型。ICE PKG 会默认把产物输出到 `esm` (输出 ES module + ES5 产物) 和 `es2017` (输出 ES module + ES2017 产物) 两个文件夹。 @@ -261,10 +262,53 @@ export default defineConfig({ - es2017 # ES module + ES2017 产物 ``` +#### entryRoot + +- 类型:`string` +- 默认值:自动推导(已配置 entry 父目录的最近公共祖先) + +用于控制 Transform 模式输出路径的相对根目录。该配置只影响产物路径映射,不影响文件处理范围。 + +例如,当 entry 是 `./src/a/b/c/index.ts`: + +- `entryRoot: './src/a/b'` 时,输出为 `esm/c/index.js` +- `entryRoot: './src'` 时,输出为 `esm/a/b/c/index.js` + +```ts title="build.config.mts" +import { defineConfig } from '@ice/pkg'; + +export default defineConfig({ + entry: './src/a/b/c/index.ts', + transform: { + formats: ['esm'], + entryRoot: './src/a/b', + }, +}); +``` + +当使用 `pkgs` 配置时,`pkgs[].entryRoot` 的优先级高于 `transform.entryRoot`。 + +```ts title="build.config.mts" +import { defineConfig } from '@ice/pkg'; + +export default defineConfig({ + transform: { + entryRoot: './src', + }, + pkgs: [ + { + id: 'button', + entry: './src/components/button/index.ts', + entryRoot: './src/components', + }, + ], +}); +``` + #### excludes -+ 类型:`string | string[]` -+ 默认值:`undefined` +- 类型:`string | string[]` +- 默认值:`undefined` 排除无需编译的文件。比如,我们不想编译 `src` 下的所有测试文件,其中测试文件包含在 `__tests__` 目录下,或以 `*.test.[j|t]s` 结尾。 @@ -286,8 +330,8 @@ export default defineConfig({ #### formats -+ 类型:`['esm', 'umd', 'cjs', 'es2017']` -+ 默认值:`['esm', 'es2017']` +- 类型:`['esm', 'umd', 'cjs', 'es2017']` +- 默认值:`['esm', 'es2017']` 输出的类型,默认是输出 `esm` 和 `es2017` 产物。 @@ -325,8 +369,8 @@ Bundle 模式的 formats 如果单独配置 `['es2017']` 将不会生效,因 #### modes -+ 类型:`Array<'development' | 'production'>` -+ 默认值:`['production']` +- 类型:`Array<'development' | 'production'>` +- 默认值:`['production']` 指定输出的产物是否经过压缩。默认情况下输出的产物是压缩过的。 @@ -356,8 +400,8 @@ export default defineConfig({ #### name -+ 类型:`string` -+ 默认值:`package.name` +- 类型:`string` +- 默认值:`package.name` library 导出的名称,可以通过 `window[name]` 访问,一般配合打包 `umd` 产物时使用。默认值为 `package.json` 配置的 `name` 字段。 @@ -366,15 +410,15 @@ import { defineConfig } from '@ice/pkg'; export default defineConfig({ bundle: { - name: 'ICEPKG' + name: 'ICEPKG', }, }); ``` #### externals -+ 类型:`boolean | Record | (string | RegExp | Record)[]` -+ 默认值:`false` +- 类型:`boolean | Record | (string | RegExp | Record)[]` +- 默认值:`false` 默认情况下,bundle 的产物包含所有依赖产物。该选项可修改这一结果。 若想要 Bundle 不包含依赖产物,可以传入 `true`,其会解析 `package.json` 并将所有依赖 external 掉,包括 node 的依赖。 @@ -420,8 +464,8 @@ export default defineConfig({ #### minify -+ 类型:`boolean | { js?: boolean | ((mode: string, command: string) => boolean | { options?: swc.JsMinifyOptions }); css?: boolean | ((mode: string, command: string) => boolean | { options?: cssnano.Options });}` -+ 默认值:build 阶段且 mode 是 `production` 时为 `true`,否则为 `false` +- 类型:`boolean | { js?: boolean | ((mode: string, command: string) => boolean | { options?: swc.JsMinifyOptions }); css?: boolean | ((mode: string, command: string) => boolean | { options?: cssnano.Options });}` +- 默认值:build 阶段且 mode 是 `production` 时为 `true`,否则为 `false` 是否压缩 JS 和 CSS 资源。 @@ -434,17 +478,25 @@ export default defineConfig({ minify: false, // 修改 JS 和 CSS 压缩参数 minify: { - js: (mode, command) => { options: { /* */ } }, - css: (mode, command) => { options: { /* */ } }, - } + js: (mode, command) => { + options: { + /* */ + } + }, + css: (mode, command) => { + options: { + /* */ + } + }, + }, }, }); ``` #### polyfill -+ 类型:`false | 'entry' | 'usage'` -+ 默认值:`'usage'` +- 类型:`false | 'entry' | 'usage'` +- 默认值:`'usage'` 配置处理 polyfill 的逻辑。不同值的含义: @@ -458,8 +510,8 @@ export default defineConfig({ #### compileDependencies -+ 类型:`boolean | RegExp[] | string[]` -+ 默认值:`false` +- 类型:`boolean | RegExp[] | string[]` +- 默认值:`false` 配置是否编译 node_modules 中的依赖。如果值为 `true`,则 node_modules 中的依赖都会编译;如果值为 false 则都不编译;如果值为数组,则只会编译对应的依赖。 @@ -475,9 +527,9 @@ export default defineConfig({ #### browser -+ 类型: `boolean` -+ 默认值: `false` -+ 可用版本: `1.6.0` +- 类型: `boolean` +- 默认值: `false` +- 可用版本: `1.6.0` 配置解析 Node 模块的时候,是否优先读取 package.json 中的 `browser` 字段。 如果你的模块**只运行**在浏览器端,可以开启此选项只 bundle 浏览器相关的代码。 @@ -500,8 +552,8 @@ export default defineConfig({ ::: -+ 类型:`boolean` -+ 默认值:`false` +- 类型:`boolean` +- 默认值:`false` 若开启该选项,则会额外输出一份 **未压缩的** 的产物,这也意味着用户可以在开发态使用该产物获得更多的开发时信息。在开发 Library 时,这将会非常有作用。