diff --git a/docs/index.html b/docs/index.html index d6287f12e..f7deb086f 100644 --- a/docs/index.html +++ b/docs/index.html @@ -1,4 +1,4 @@ - + diff --git a/package.json b/package.json index 0d016a999..ab9998c11 100644 --- a/package.json +++ b/package.json @@ -59,7 +59,7 @@ "fs-extra": "10.0.0", "postcss": "8.4.12", "postcss-simple-vars": "6.0.3", - "prettier": "2.5.1", + "prettier": "3.3.3", "resolve": "1.20.0", "rollup-plugin-dts": "6.1.0", "sass": "1.62.1", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index b97ae6487..ac29b6657 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -92,8 +92,8 @@ devDependencies: specifier: 6.0.3 version: 6.0.3(postcss@8.4.12) prettier: - specifier: 2.5.1 - version: 2.5.1 + specifier: 3.3.3 + version: 3.3.3 resolve: specifier: 1.20.0 version: 1.20.0 @@ -2031,9 +2031,9 @@ packages: source-map-js: 1.2.0 dev: true - /prettier@2.5.1: - resolution: {integrity: sha512-vBZcPRUR5MZJwoyi3ZoyQlc1rXeEck8KgeC9AwwOn+exuxLxq5toTRDTSaVrXHxelDMHy9zlicw8u66yxoSUFg==} - engines: {node: '>=10.13.0'} + /prettier@3.3.3: + resolution: {integrity: sha512-i2tDNA0O5IrMO757lfrdQZCc2jPNDVntV0m/+4whiDfWaTKfMNgR7Qz0NAeGz/nRqF4m5/6CLzbP4/liHt12Ew==} + engines: {node: '>=14'} hasBin: true dev: true diff --git a/src/api-extractor.ts b/src/api-extractor.ts index 8e269e9ec..f911cf1d5 100644 --- a/src/api-extractor.ts +++ b/src/api-extractor.ts @@ -27,7 +27,7 @@ const logger = createLogger() function rollupDtsFile( inputFilePath: string, outputFilePath: string, - tsconfigFilePath: string + tsconfigFilePath: string, ) { let cwd = process.cwd() let packageJsonFullPath = path.join(cwd, 'package.json') @@ -59,7 +59,7 @@ function rollupDtsFile( const imported = getApiExtractor() if (!imported) { throw new Error( - `@microsoft/api-extractor is not installed. Please install it first.` + `@microsoft/api-extractor is not installed. Please install it first.`, ) } const { ExtractorConfig, Extractor } = imported @@ -77,7 +77,7 @@ function rollupDtsFile( if (!extractorResult.succeeded) { throw new Error( - `API Extractor completed with ${extractorResult.errorCount} errors and ${extractorResult.warningCount} warnings when processing ${inputFilePath}` + `API Extractor completed with ${extractorResult.errorCount} errors and ${extractorResult.warningCount} warnings when processing ${inputFilePath}`, ) } } @@ -85,7 +85,7 @@ function rollupDtsFile( async function rollupDtsFiles( options: NormalizedOptions, exports: ExportDeclaration[], - format: Format + format: Format, ) { let declarationDir = ensureTempDeclarationDir() let outDir = options.outDir || 'dist' @@ -94,7 +94,7 @@ async function rollupDtsFiles( let dtsInputFilePath = path.join( declarationDir, - '_tsup-dts-aggregation' + dtsExtension + '_tsup-dts-aggregation' + dtsExtension, ) // @microsoft/api-extractor doesn't support `.d.mts` and `.d.cts` file as a // entrypoint yet. So we replace the extension here as a temporary workaround. @@ -109,29 +109,29 @@ async function rollupDtsFiles( writeFileSync( dtsInputFilePath, - formatAggregationExports(exports, declarationDir) + formatAggregationExports(exports, declarationDir), ) rollupDtsFile( dtsInputFilePath, dtsOutputFilePath, - options.tsconfig || 'tsconfig.json' + options.tsconfig || 'tsconfig.json', ) for (let [out, sourceFileName] of Object.entries( - options.experimentalDts!.entry + options.experimentalDts!.entry, )) { sourceFileName = toAbsolutePath(sourceFileName) const outFileName = path.join(outDir, out + dtsExtension) // Find all declarations that are exported from the current source file const currentExports = exports.filter( - (declaration) => declaration.sourceFileName === sourceFileName + (declaration) => declaration.sourceFileName === sourceFileName, ) writeFileSync( outFileName, - formatDistributionExports(currentExports, outFileName, dtsOutputFilePath) + formatDistributionExports(currentExports, outFileName, dtsOutputFilePath), ) } } @@ -144,7 +144,7 @@ function cleanDtsFiles(options: NormalizedOptions) { export async function runDtsRollup( options: NormalizedOptions, - exports?: ExportDeclaration[] + exports?: ExportDeclaration[], ) { try { const start = Date.now() diff --git a/src/cli-main.ts b/src/cli-main.ts index 58f9dad09..ce5b64d74 100644 --- a/src/cli-main.ts +++ b/src/cli-main.ts @@ -26,44 +26,44 @@ export async function main(options: Options = {}) { .option('--minify-syntax', 'Minify syntax') .option( '--keep-names', - 'Keep original function and class names in minified code' + 'Keep original function and class names in minified code', ) .option('--target ', 'Bundle target, "es20XX" or "esnext"', { default: 'es2017', }) .option( '--legacy-output', - 'Output different formats to different folder instead of using different extensions' + 'Output different formats to different folder instead of using different extensions', ) .option('--dts [entry]', 'Generate declaration file') .option('--dts-resolve', 'Resolve externals types used for d.ts files') .option('--dts-only', 'Emit declaration files only') .option( '--experimental-dts [entry]', - 'Generate declaration file (experimental)' + 'Generate declaration file (experimental)', ) .option( '--sourcemap [inline]', - 'Generate external sourcemap, or inline source: --sourcemap inline' + 'Generate external sourcemap, or inline source: --sourcemap inline', ) .option( '--watch [path]', - 'Watch mode, if path is not specified, it watches the current folder ".". Repeat "--watch" for more than one path' + 'Watch mode, if path is not specified, it watches the current folder ".". Repeat "--watch" for more than one path', ) .option('--ignore-watch ', 'Ignore custom paths in watch mode') .option( '--onSuccess ', - 'Execute command after successful build, specially useful for watch mode' + 'Execute command after successful build, specially useful for watch mode', ) .option('--env.* ', 'Define compile-time env variables') .option( '--inject ', - 'Replace a global variable with an import from another file' + 'Replace a global variable with an import from another file', ) .option('--define.* ', 'Define compile-time constants') .option( '--external ', - 'Mark specific packages / package.json (dependencies and peerDependencies) as external' + 'Mark specific packages / package.json (dependencies and peerDependencies) as external', ) .option('--global-name ', 'Global variable name for iife format') .option('--jsxFactory ', 'Name of JSX factory function', { @@ -77,7 +77,7 @@ export async function main(options: Options = {}) { .option('--clean', 'Clean output directory') .option( '--silent', - 'Suppress non-error logs (excluding "onSuccess" process output)' + 'Suppress non-error logs (excluding "onSuccess" process output)', ) .option('--pure ', 'Mark specific expressions as pure') .option('--metafile', 'Emit esbuild metafile (a JSON file)') @@ -92,12 +92,12 @@ export async function main(options: Options = {}) { .option('--inject-style', 'Inject style tag to document head') .option( '--treeshake [strategy]', - 'Using Rollup for treeshaking instead, "recommended" or "smallest" or "safest"' + 'Using Rollup for treeshaking instead, "recommended" or "smallest" or "safest"', ) .option('--publicDir [dir]', 'Copy public directory to output directory') .option( '--killSignal ', - 'Signal to kill child process, "SIGTERM" or "SIGKILL"' + 'Signal to kill child process, "SIGTERM" or "SIGKILL"', ) .option('--cjsInterop', 'Enable cjs interop') .action(async (files: string[], flags) => { diff --git a/src/errors.ts b/src/errors.ts index 07aa65f95..d58fa369e 100644 --- a/src/errors.ts +++ b/src/errors.ts @@ -18,9 +18,9 @@ export function handleError(error: any) { console.error( colors.bold( colors.red( - `Error parsing: ${error.loc.file}:${error.loc.line}:${error.loc.column}` - ) - ) + `Error parsing: ${error.loc.file}:${error.loc.line}:${error.loc.column}`, + ), + ), ) } if (error.frame) { diff --git a/src/esbuild/external.ts b/src/esbuild/external.ts index 868d0773b..c4255b377 100644 --- a/src/esbuild/external.ts +++ b/src/esbuild/external.ts @@ -21,7 +21,7 @@ export const externalPlugin = ({ setup(build) { if (skipNodeModulesBundle) { const resolvePatterns = tsconfigPathsToRegExp( - tsconfigResolvePaths || {} + tsconfigResolvePaths || {}, ) build.onResolve({ filter: /.*/ }, (args) => { // Resolve `paths` from tsconfig diff --git a/src/esbuild/index.ts b/src/esbuild/index.ts index aec991d05..22ba0aaa2 100644 --- a/src/esbuild/index.ts +++ b/src/esbuild/index.ts @@ -23,7 +23,7 @@ import { OutExtensionFactory } from '../options' const getOutputExtensionMap = ( options: NormalizedOptions, format: Format, - pkgType: string | undefined + pkgType: string | undefined, ) => { const outExtension: OutExtensionFactory = options.outExtension || defaultOutExtension @@ -72,7 +72,7 @@ export async function runEsbuild( buildDependencies: Set logger: Logger pluginContainer: PluginContainer - } + }, ) { const pkg = await loadPkg(process.cwd()) const deps = await getProductionDeps(process.cwd()) @@ -103,8 +103,8 @@ export async function runEsbuild( format === 'iife' ? false : typeof options.splitting === 'boolean' - ? options.splitting - : format === 'esm' + ? options.splitting + : format === 'esm' const platform = options.platform || 'node' const loader = options.loader || {} @@ -251,7 +251,7 @@ export async function runEsbuild( const messages = result.warnings.filter((warning) => { if ( warning.text.includes( - `This call to "require" will not be bundled because` + `This call to "require" will not be bundled because`, ) || warning.text.includes(`Indirect calls to "require" will not be bundled`) ) @@ -290,7 +290,7 @@ export async function runEsbuild( await fs.promises.writeFile( outPath, JSON.stringify(result.metafile), - 'utf8' + 'utf8', ) } } diff --git a/src/esbuild/native-node-module.ts b/src/esbuild/native-node-module.ts index 6d61b98d9..955921ce2 100644 --- a/src/esbuild/native-node-module.ts +++ b/src/esbuild/native-node-module.ts @@ -44,7 +44,7 @@ export const nativeNodeModulesPlugin = (): Plugin => { (args) => ({ path: args.path, namespace: 'file', - }) + }), ) // Tell esbuild's default loading behavior to use the "file" loader for diff --git a/src/esbuild/node-protocol.ts b/src/esbuild/node-protocol.ts index a35e0abd5..885452df6 100644 --- a/src/esbuild/node-protocol.ts +++ b/src/esbuild/node-protocol.ts @@ -17,7 +17,7 @@ export const nodeProtocolPlugin = (): Plugin => { ({ path }) => ({ path: path.slice(nodeProtocol.length), external: true, - }) + }), ) }, } diff --git a/src/esbuild/postcss.ts b/src/esbuild/postcss.ts index 14d6cfb23..1dbcc7a78 100644 --- a/src/esbuild/postcss.ts +++ b/src/esbuild/postcss.ts @@ -74,7 +74,7 @@ export const postcssPlugin = ({ `, loader: 'js', } - } + }, ) build.onLoad({ filter: /\.css$/ }, async (args) => { @@ -126,7 +126,7 @@ export const postcssPlugin = ({ typeof inject === 'function' ? inject(JSON.stringify(contents), args.path) : `import styleInject from '#style-inject';styleInject(${JSON.stringify( - contents + contents, )})` return { diff --git a/src/esbuild/svelte.ts b/src/esbuild/svelte.ts index 0a3401833..aa3d9d353 100644 --- a/src/esbuild/svelte.ts +++ b/src/esbuild/svelte.ts @@ -22,7 +22,7 @@ export const sveltePlugin = ({ return { path: path.relative( process.cwd(), - path.join(args.resolveDir, args.path) + path.join(args.resolveDir, args.path), ), namespace: 'svelte-css', } @@ -97,7 +97,7 @@ export const sveltePlugin = ({ }, { filename: args.path, - } + }, ) const result = svelte.compile(preprocess.code, { filename, diff --git a/src/esbuild/swc.ts b/src/esbuild/swc.ts index c0ab2b20a..c03e30b9f 100644 --- a/src/esbuild/swc.ts +++ b/src/esbuild/swc.ts @@ -17,7 +17,7 @@ export const swcPlugin = ({ logger }: { logger: Logger }): Plugin => { if (!swc) { logger.warn( build.initialOptions.format!, - `You have emitDecoratorMetadata enabled but @swc/core was not installed, skipping swc plugin` + `You have emitDecoratorMetadata enabled but @swc/core was not installed, skipping swc plugin`, ) return } @@ -58,7 +58,7 @@ export const swcPlugin = ({ logger }: { logger: Logger }): Plugin => { : source }) code += `//# sourceMappingURL=data:application/json;base64,${Buffer.from( - JSON.stringify(map) + JSON.stringify(map), ).toString('base64')}` } return { diff --git a/src/exports.ts b/src/exports.ts index c1fdf3e24..7b320a77f 100644 --- a/src/exports.ts +++ b/src/exports.ts @@ -22,11 +22,11 @@ interface NamedExport { export function formatAggregationExports( exports: ExportDeclaration[], - declarationDirPath: string + declarationDirPath: string, ): string { const lines = exports .map((declaration) => - formatAggregationExport(declaration, declarationDirPath) + formatAggregationExport(declaration, declarationDirPath), ) .filter(truthy) @@ -39,13 +39,13 @@ export function formatAggregationExports( function formatAggregationExport( declaration: ExportDeclaration, - declarationDirPath: string + declarationDirPath: string, ): string { let dest = trimDtsExtension( './' + path.posix.normalize( - slash(path.relative(declarationDirPath, declaration.destFileName)) - ) + slash(path.relative(declarationDirPath, declaration.destFileName)), + ), ) if (declaration.kind === 'module') { @@ -71,13 +71,13 @@ function formatAggregationExport( export function formatDistributionExports( exports: ExportDeclaration[], fromFilePath: string, - toFilePath: string + toFilePath: string, ) { let importPath = trimDtsExtension( path.posix.relative( path.posix.dirname(path.posix.normalize(slash(fromFilePath))), - path.posix.normalize(slash(toFilePath)) - ) + path.posix.normalize(slash(toFilePath)), + ), ) if (!importPath.match(/^\.+\//)) { importPath = './' + importPath @@ -118,7 +118,7 @@ export function formatDistributionExports( function formatDistributionExport( declaration: ExportDeclaration, - dest: string + dest: string, ): string { if (declaration.kind === 'named') { return [ diff --git a/src/fs.ts b/src/fs.ts index 9a20522f0..3adb4f142 100644 --- a/src/fs.ts +++ b/src/fs.ts @@ -4,7 +4,7 @@ import fs from 'fs' export const outputFile = async ( filepath: string, data: any, - options?: { mode?: fs.Mode } + options?: { mode?: fs.Mode }, ) => { await fs.promises.mkdir(path.dirname(filepath), { recursive: true }) await fs.promises.writeFile(filepath, data, options) diff --git a/src/index.ts b/src/index.ts index 6b2b1b2e9..3b981c555 100644 --- a/src/index.ts +++ b/src/index.ts @@ -39,8 +39,8 @@ export const defineConfig = ( | Options[] | (( /** The options derived from CLI flags */ - overrideOptions: Options - ) => MaybePromise) + overrideOptions: Options, + ) => MaybePromise), ) => options /** @@ -70,7 +70,7 @@ const killProcess = ({ pid, signal }: { pid: number; signal: KILL_SIGNAL }) => const normalizeOptions = async ( logger: ReturnType, optionsFromConfigFile: Options | undefined, - optionsOverride: Options + optionsOverride: Options, ) => { const _options = { ...optionsFromConfigFile, @@ -90,21 +90,21 @@ const normalizeOptions = async ( ? {} : undefined : typeof _options.dts === 'string' - ? { entry: _options.dts } - : _options.dts, + ? { entry: _options.dts } + : _options.dts, experimentalDts: _options.experimentalDts ? typeof _options.experimentalDts === 'boolean' ? _options.experimentalDts ? { entry: {} } : undefined : typeof _options.experimentalDts === 'string' - ? { - entry: toObjectEntry(_options.experimentalDts), - } - : { - ..._options.experimentalDts, - entry: toObjectEntry(_options.experimentalDts.entry || {}), - } + ? { + entry: toObjectEntry(_options.experimentalDts), + } + : { + ..._options.experimentalDts, + entry: toObjectEntry(_options.experimentalDts.entry || {}), + } : undefined, } @@ -139,7 +139,7 @@ const normalizeOptions = async ( if (tsconfig) { logger.info( 'CLI', - `Using tsconfig: ${path.relative(process.cwd(), tsconfig.path)}` + `Using tsconfig: ${path.relative(process.cwd(), tsconfig.path)}`, ) options.tsconfig = tsconfig.path options.tsconfigResolvePaths = tsconfig.data?.compilerOptions?.paths || {} @@ -159,7 +159,7 @@ const normalizeOptions = async ( options.experimentalDts.entry = toObjectEntry( Object.keys(options.experimentalDts.entry).length > 0 ? options.experimentalDts.entry - : options.entry + : options.entry, ) } if (!options.target) { @@ -182,7 +182,7 @@ export async function build(_options: Options) { ? {} : await loadTsupConfig( process.cwd(), - _options.config === true ? undefined : _options.config + _options.config === true ? undefined : _options.config, ) const configData = @@ -209,7 +209,7 @@ export async function build(_options: Options) { const dtsTask = async () => { if (options.dts && options.experimentalDts) { throw new Error( - "You can't use both `dts` and `experimentalDts` at the same time" + "You can't use both `dts` and `experimentalDts` at the same time", ) } @@ -281,7 +281,7 @@ export async function build(_options: Options) { return buildAll() }, 100, - handleError + handleError, ) const buildAll = async () => { @@ -335,7 +335,7 @@ export async function build(_options: Options) { buildDependencies, }).catch((error) => { previousBuildDependencies.forEach((v) => - buildDependencies.add(v) + buildDependencies.add(v), ) throw error }) @@ -380,10 +380,10 @@ export async function build(_options: Options) { typeof options.watch === 'boolean' ? '.' : Array.isArray(options.watch) - ? options.watch.filter( - (path): path is string => typeof path === 'string' - ) - : options.watch + ? options.watch.filter( + (path): path is string => typeof path === 'string', + ) + : options.watch logger.info( 'CLI', @@ -391,13 +391,13 @@ export async function build(_options: Options) { Array.isArray(watchPaths) ? watchPaths.map((v) => '"' + v + '"').join(' | ') : '"' + watchPaths + '"' - }` + }`, ) logger.info( 'CLI', `Ignoring changes in ${ignored .map((v) => '"' + v + '"') - .join(' | ')}` + .join(' | ')}`, ) const watcher = watch(watchPaths, { @@ -451,7 +451,7 @@ export async function build(_options: Options) { } await Promise.all([dtsTask(), mainTasks()]) - } - ) + }, + ), ) } diff --git a/src/lib/public-dir.ts b/src/lib/public-dir.ts index 7179d467b..f15459e96 100644 --- a/src/lib/public-dir.ts +++ b/src/lib/public-dir.ts @@ -4,7 +4,7 @@ import { slash } from '../utils' export const copyPublicDir = ( publicDir: string | boolean | undefined, - outDir: string + outDir: string, ) => { if (!publicDir) return copyDirSync(path.resolve(publicDir === true ? 'public' : publicDir), outDir) @@ -12,11 +12,11 @@ export const copyPublicDir = ( export const isInPublicDir = ( publicDir: string | boolean | undefined, - filePath: string + filePath: string, ) => { if (!publicDir) return false const publicPath = slash( - path.resolve(publicDir === true ? 'public' : publicDir) + path.resolve(publicDir === true ? 'public' : publicDir), ) return slash(path.resolve(filePath)).startsWith(`${publicPath}/`) } diff --git a/src/lib/report-size.ts b/src/lib/report-size.ts index f121502e7..6f0d5504b 100644 --- a/src/lib/report-size.ts +++ b/src/lib/report-size.ts @@ -21,7 +21,7 @@ const padRight = (str: string, maxLength: number) => { export const reportSize = ( logger: Logger, format: string, - files: { [name: string]: number } + files: { [name: string]: number }, ) => { const filenames = Object.keys(files) const maxLength = getLengthOfLongestString(filenames) + 1 @@ -29,8 +29,8 @@ export const reportSize = ( logger.success( format, `${colors.bold(padRight(name, maxLength))}${colors.green( - prettyBytes(files[name]) - )}` + prettyBytes(files[name]), + )}`, ) } } diff --git a/src/load.ts b/src/load.ts index bda258ec8..98d389fc5 100644 --- a/src/load.ts +++ b/src/load.ts @@ -15,7 +15,7 @@ const loadJson = async (filepath: string) => { throw new Error( `Failed to parse ${path.relative(process.cwd(), filepath)}: ${ error.message - }` + }`, ) } else { throw error @@ -34,7 +34,7 @@ joycon.addLoader(jsonLoader) export async function loadTsupConfig( cwd: string, - configFile?: string + configFile?: string, ): Promise<{ path?: string; data?: ReturnType }> { const configJoycon = new JoyCon() const configPath = await configJoycon.resolve({ @@ -90,7 +90,7 @@ export async function loadPkg(cwd: string, clearCache: boolean = false) { */ export async function getProductionDeps( cwd: string, - clearCache: boolean = false + clearCache: boolean = false, ) { const data = await loadPkg(cwd, clearCache) @@ -98,7 +98,7 @@ export async function getProductionDeps( new Set([ ...Object.keys(data.dependencies || {}), ...Object.keys(data.peerDependencies || {}), - ]) + ]), ) return deps diff --git a/src/log.ts b/src/log.ts index 0c1cd4985..bedfc55ac 100644 --- a/src/log.ts +++ b/src/log.ts @@ -11,17 +11,17 @@ export const colorize = (type: LOG_TYPE, data: any, onlyImportant = false) => { type === 'info' ? 'blue' : type === 'error' - ? 'red' - : type === 'warn' - ? 'yellow' - : 'green' + ? 'red' + : type === 'warn' + ? 'yellow' + : 'green' return colors[color](data) } export const makeLabel = ( name: string | undefined, input: string, - type: LOG_TYPE + type: LOG_TYPE, ) => { return [ name && `${colors.dim('[')}${name.toUpperCase()}${colors.dim(']')}`, diff --git a/src/options.ts b/src/options.ts index 0921abdae..a362a1f04 100644 --- a/src/options.ts +++ b/src/options.ts @@ -19,7 +19,7 @@ export type ContextForOutPathGeneration = { export type OutExtensionObject = { js?: string; dts?: string } export type OutExtensionFactory = ( - ctx: ContextForOutPathGeneration + ctx: ContextForOutPathGeneration, ) => OutExtensionObject export type DtsConfig = { diff --git a/src/plugin.ts b/src/plugin.ts index d42410a7f..1a3222055 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -30,7 +30,7 @@ export type AssetInfo = { export type RenderChunk = ( this: PluginContext, code: string, - chunkInfo: ChunkInfo + chunkInfo: ChunkInfo, ) => MaybePromise< | { code: string @@ -44,12 +44,12 @@ export type RenderChunk = ( export type BuildStart = (this: PluginContext) => MaybePromise export type BuildEnd = ( this: PluginContext, - ctx: { writtenFiles: WrittenFile[] } + ctx: { writtenFiles: WrittenFile[] }, ) => MaybePromise export type ModifyEsbuildOptions = ( this: PluginContext, - options: EsbuildOptions + options: EsbuildOptions, ) => void export type Plugin = { @@ -149,16 +149,16 @@ export class PluginContainer { const result = await plugin.renderChunk.call( this.getContext(), info.code, - info + info, ) if (result) { info.code = result.code if (result.map) { const originalConsumer = await new SourceMapConsumer( - parseSourceMap(info.map) + parseSourceMap(info.map), ) const newConsumer = await new SourceMapConsumer( - parseSourceMap(result.map) + parseSourceMap(result.map), ) const generator = SourceMapGenerator.fromSourceMap(originalConsumer) @@ -179,7 +179,7 @@ export class PluginContainer { inlineSourceMap, info.map, info.path, - isCSS(info.path) + isCSS(info.path), ) : info.contents await outputFile(info.path, contents, { @@ -208,7 +208,7 @@ export class PluginContainer { }, }) } - }) + }), ) for (const plugin of this.plugins) { @@ -223,14 +223,14 @@ const getSourcemapComment = ( inline: boolean, map: RawSourceMap | string | null | undefined, filepath: string, - isCssFile: boolean + isCssFile: boolean, ) => { if (!map) return '' const prefix = isCssFile ? '/*' : '//' const suffix = isCssFile ? ' */' : '' const url = inline ? `data:application/json;base64,${Buffer.from( - typeof map === 'string' ? map : JSON.stringify(map) + typeof map === 'string' ? map : JSON.stringify(map), ).toString('base64')}` : `${path.basename(filepath)}.map` return `${prefix}# sourceMappingURL=${url}${suffix}` diff --git a/src/plugins/size-reporter.ts b/src/plugins/size-reporter.ts index 2239ed9f5..ebc44a13b 100644 --- a/src/plugins/size-reporter.ts +++ b/src/plugins/size-reporter.ts @@ -14,7 +14,7 @@ export const sizeReporter = (): Plugin => { ...res, [file.name]: file.size, } - }, {}) + }, {}), ) }, } diff --git a/src/plugins/swc-target.ts b/src/plugins/swc-target.ts index 757fc759f..cf0d629d2 100644 --- a/src/plugins/swc-target.ts +++ b/src/plugins/swc-target.ts @@ -1,4 +1,4 @@ -import type { ModuleConfig } from '@swc/core/types'; +import type { ModuleConfig } from '@swc/core/types' import { PrettyError } from '../errors' import { Plugin } from '../plugin' import { localRequire } from '../utils' @@ -7,7 +7,7 @@ const TARGETS = ['es5', 'es3'] as const export const swcTarget = (): Plugin => { let enabled = false - let target: typeof TARGETS[number] + let target: (typeof TARGETS)[number] return { name: 'swc-target', @@ -31,7 +31,7 @@ export const swcTarget = (): Plugin => { if (!swc) { throw new PrettyError( - `@swc/core is required for ${target} target. Please install it with \`npm install @swc/core -D\`` + `@swc/core is required for ${target} target. Please install it with \`npm install @swc/core -D\``, ) } @@ -57,7 +57,7 @@ export const swcTarget = (): Plugin => { : undefined, }, module: { - type: this.format === 'cjs' ? 'commonjs' : 'es6' + type: this.format === 'cjs' ? 'commonjs' : 'es6', } as ModuleConfig, }) return { diff --git a/src/plugins/terser.ts b/src/plugins/terser.ts index c8b6ef0c7..6ed798912 100644 --- a/src/plugins/terser.ts +++ b/src/plugins/terser.ts @@ -29,7 +29,7 @@ export const terserPlugin = ({ if (!terser) { throw new PrettyError( - 'terser is required for terser minification. Please install it with `npm install terser -D`' + 'terser is required for terser minification. Please install it with `npm install terser -D`', ) } @@ -46,7 +46,7 @@ export const terserPlugin = ({ try { const minifiedOutput = await minify( { [info.path]: code }, - { ...defaultOptions, ...terserOptions } + { ...defaultOptions, ...terserOptions }, ) logger.info('TERSER', 'Minifying with Terser') diff --git a/src/rollup.ts b/src/rollup.ts index a7dd07801..947d6c2fa 100644 --- a/src/rollup.ts +++ b/src/rollup.ts @@ -19,7 +19,7 @@ const parseCompilerOptions = (compilerOptions?: any) => { const { options } = ts.parseJsonConfigFileContent( { compilerOptions }, ts.sys, - './' + './', ) return options } @@ -35,7 +35,7 @@ type RollupConfig = { } const getRollupConfig = async ( - options: NormalizedOptions + options: NormalizedOptions, ): Promise => { setSilent(options.silent) @@ -60,7 +60,7 @@ const getRollupConfig = async ( // `paths` should be handled by rollup-plugin-dts if (compilerOptions.paths) { const res = Object.keys(compilerOptions.paths).map( - (p) => new RegExp(`^${p.replace('*', '.+')}$`) + (p) => new RegExp(`^${p.replace('*', '.+')}$`), ) tsResolveOptions.ignore = (source) => { return res.some((re) => re.test(source)) @@ -103,7 +103,7 @@ const getRollupConfig = async ( return code.replace( /(?<=(?<=[;}]|^)\s*export\s*){\s*([\w$]+)\s*as\s+default\s*}/, - `= $1` + `= $1`, ) }, } @@ -192,13 +192,13 @@ async function runRollup(options: RollupConfig) { outputs.reduce((res, info) => { const name = path.relative( process.cwd(), - path.join(options.outputConfig[0].dir || '.', info.fileName) + path.join(options.outputConfig[0].dir || '.', info.fileName), ) return { ...res, [name]: info.type === 'chunk' ? info.code.length : info.source.length, } - }, {}) + }, {}), ) } catch (error) { handleError(error) diff --git a/src/rollup/ts-resolve.ts b/src/rollup/ts-resolve.ts index bf3dd2894..4b3339f84 100644 --- a/src/rollup/ts-resolve.ts +++ b/src/rollup/ts-resolve.ts @@ -9,7 +9,7 @@ const debug = createDebug('tsup:ts-resolve') const resolveModule = ( id: string, - opts: _resolve.AsyncOpts + opts: _resolve.AsyncOpts, ): Promise => new Promise((resolve, reject) => { _resolve(id, opts, (err, res) => { diff --git a/src/tsc.ts b/src/tsc.ts index 9094dd768..c7677b029 100644 --- a/src/tsc.ts +++ b/src/tsc.ts @@ -20,7 +20,7 @@ class AliasPool { alias = `${name}_alias_${++suffix}` if (suffix >= 1000) { throw new Error( - 'Alias generation exceeded limit. Possible infinite loop detected.' + 'Alias generation exceeded limit. Possible infinite loop detected.', ) } } @@ -35,7 +35,7 @@ class AliasPool { */ function getExports( program: ts.Program, - fileMapping: Map + fileMapping: Map, ): ExportDeclaration[] { let checker = program.getTypeChecker() let aliasPool = new AliasPool() @@ -95,7 +95,7 @@ function emitDtsFiles(program: ts.Program, host: ts.CompilerHost) { writeByteOrderMark, onError, sourceFiles, - data + data, ) => { const sourceFile = sourceFiles?.[0] let sourceFileName = sourceFile?.fileName @@ -104,7 +104,7 @@ function emitDtsFiles(program: ts.Program, host: ts.CompilerHost) { const cwd = program.getCurrentDirectory() fileMapping.set( toAbsolutePath(sourceFileName, cwd), - toAbsolutePath(fileName, cwd) + toAbsolutePath(fileName, cwd), ) } @@ -114,7 +114,7 @@ function emitDtsFiles(program: ts.Program, host: ts.CompilerHost) { writeByteOrderMark, onError, sourceFiles, - data + data, ) } @@ -130,19 +130,19 @@ function emitDtsFiles(program: ts.Program, host: ts.CompilerHost) { if (diagnostic.file) { let { line, character } = ts.getLineAndCharacterOfPosition( diagnostic.file, - diagnostic.start! + diagnostic.start!, ) let message = ts.flattenDiagnosticMessageText( diagnostic.messageText, - '\n' + '\n', ) diagnosticMessages.push( - `${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}` + `${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`, ) } else { let message = ts.flattenDiagnosticMessageText( diagnostic.messageText, - '\n' + '\n', ) diagnosticMessages.push(message) } @@ -152,7 +152,7 @@ function emitDtsFiles(program: ts.Program, host: ts.CompilerHost) { if (diagnosticMessage) { logger.error( 'TSC', - 'Failed to emit declaration files.\n\n' + diagnosticMessage + 'Failed to emit declaration files.\n\n' + diagnosticMessage, ) throw new Error('TypeScript compilation failed') } @@ -184,7 +184,7 @@ function emit(compilerOptions?: any, tsconfig?: string) { }, }, ts.sys, - tsconfig ? dirname(tsconfig) : './' + tsconfig ? dirname(tsconfig) : './', ) let options: ts.CompilerOptions = parsedTsconfig.options @@ -193,7 +193,7 @@ function emit(compilerOptions?: any, tsconfig?: string) { let program: ts.Program = ts.createProgram( parsedTsconfig.fileNames, options, - host + host, ) let fileMapping = emitDtsFiles(program, host) diff --git a/src/utils.ts b/src/utils.ts index cc7f6b7ca..de2be90b1 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -15,7 +15,7 @@ export type External = export function isExternal( externals: External | External[], id: string, - parentId?: string + parentId?: string, ) { id = slash(id) @@ -79,7 +79,7 @@ export async function removeFiles(patterns: string[], dir: string) { export function debouncePromise( fn: (...args: T) => Promise, delay: number, - onError: (err: unknown) => void + onError: (err: unknown) => void, ) { let timeout: ReturnType | undefined @@ -193,16 +193,19 @@ export const toObjectEntry = (entry: string | Entry) => { } entry = entry.map((e) => e.replace(/\\/g, '/')) const ancestor = findLowestCommonAncestor(entry) - return entry.reduce((result, item) => { - const key = item - .replace(ancestor, '') - .replace(/^\//, '') - .replace(/\.[a-z]+$/, '') - return { - ...result, - [key]: item, - } - }, {} as Record) + return entry.reduce( + (result, item) => { + const key = item + .replace(ancestor, '') + .replace(/^\//, '') + .replace(/\.[a-z]+$/, '') + return { + ...result, + [key]: item, + } + }, + {} as Record, + ) } const findLowestCommonAncestor = (filepaths: string[]) => { diff --git a/test/index.test.ts b/test/index.test.ts index 71c946a21..8156f39da 100644 --- a/test/index.test.ts +++ b/test/index.test.ts @@ -43,7 +43,7 @@ async function run( entry?: string[] flags?: string[] env?: Record - } = {} + } = {}, ) { const testDir = path.resolve(cacheDir, filenamify(title)) @@ -51,7 +51,7 @@ async function run( await Promise.all( Object.keys(files).map((name) => { return fs.outputFile(path.resolve(testDir, name), files[name], 'utf8') - }) + }), ) const entry = options.entry || ['input.ts'] @@ -63,7 +63,7 @@ async function run( { cwd: testDir, env: { ...process.env, ...options.env }, - } + }, ) const logs = stdout + stderr if (exitCode !== 0) { @@ -113,7 +113,7 @@ test('bundle graphql-tools with --dts flag', async () => { }, { flags: ['--dts'], - } + }, ) }) @@ -125,7 +125,7 @@ test('bundle graphql-tools with --dts-resolve flag', async () => { }, { flags: ['--dts-resolve'], - } + }, ) }) @@ -139,7 +139,7 @@ test('bundle vue and ts-essentials with --dts --dts-resolve flag', async () => { }, { flags: ['--dts', '--dts-resolve'], - } + }, ) }) @@ -156,7 +156,7 @@ test('bundle @egoist/path-parser with --dts --dts-resolve flag', async () => { }, { flags: ['--dts', '--dts-resolve'], - } + }, ) }) @@ -171,7 +171,7 @@ test('not bundle `package/subpath` in dts (resolve)', async () => { }, { flags: ['--dts', '--dts-resolve'], - } + }, ) const content = await getFileContent('dist/input.d.ts') expect(content).toMatchSnapshot() @@ -206,7 +206,7 @@ test('bundle graphql-tools with --sourcemap flag', async () => { }, { flags: ['--sourcemap'], - } + }, ) expect(outFiles).toEqual(['input.js', 'input.js.map']) }) @@ -219,7 +219,7 @@ test('bundle graphql-tools with --sourcemap inline flag', async () => { }, { flags: ['--sourcemap', 'inline'], - } + }, ) expect(output).toContain('//# sourceMappingURL=data:application/json;base64') @@ -236,7 +236,7 @@ test('multiple formats', async () => { }, { flags: ['--format', 'esm,cjs,iife'], - } + }, ) expect(outFiles).toEqual(['input.global.js', 'input.js', 'input.mjs']) @@ -253,7 +253,7 @@ test('multiple formats and pkg.type is module', async () => { }, { flags: ['--format', 'esm,cjs,iife'], - } + }, ) expect(outFiles).toEqual(['input.cjs', 'input.global.js', 'input.js']) @@ -271,7 +271,7 @@ test('minify', async () => { }, { flags: ['--minify'], - } + }, ) expect(output).toContain(`return"foo"`) @@ -290,7 +290,7 @@ test('minify with es5 target', async () => { }, { flags: ['--minify', '--target', 'es5'], - } + }, ) expect(output).toContain(`return"foo"`) @@ -307,7 +307,7 @@ test('env flag', async () => { }, { flags: ['--env.NODE_ENV', 'production'], - } + }, ) expect(output).toContain('var env = "production"') @@ -373,7 +373,7 @@ test('import css in --dts', async () => { } `, }, - { flags: ['--dts'] } + { flags: ['--dts'] }, ) expect(output).toMatchSnapshot() @@ -444,7 +444,7 @@ test('disable code splitting to get proper module.exports =', async () => { }, { flags: ['--no-splitting'], - } + }, ) expect(output).toMatchSnapshot() }) @@ -471,7 +471,7 @@ test('bundle svelte', async () => { { // To make the snapshot leaner flags: ['--external', 'svelte/internal'], - } + }, ) expect(output).not.toContain('