diff --git a/cspell.config.cjs b/cspell.config.cjs index f7e434766..81686c741 100644 --- a/cspell.config.cjs +++ b/cspell.config.cjs @@ -18,6 +18,7 @@ module.exports = { 'node_modules', 'pnpm-lock.yaml', ], + words: ['parseable', 'opencollective'], flagWords: banWords, dictionaries: ['dictionary'], dictionaryDefinitions: [ diff --git a/examples/zero-configuration/README.md b/examples/zero-configuration/README.md new file mode 100644 index 000000000..84f898498 --- /dev/null +++ b/examples/zero-configuration/README.md @@ -0,0 +1,3 @@ +# @examples/zero-configuration + +This example demonstrates how to use Rslib's zero configuration feature. diff --git a/examples/zero-configuration/package.json b/examples/zero-configuration/package.json new file mode 100644 index 000000000..46a66ba7f --- /dev/null +++ b/examples/zero-configuration/package.json @@ -0,0 +1,12 @@ +{ + "name": "@examples/zero-configuration", + "private": true, + "scripts": { + "build": "rslib build" + }, + "dependencies": {}, + "devDependencies": { + "@rslib/core": "workspace:*", + "typescript": "^5.5.4" + } +} diff --git a/examples/zero-configuration/src/index.ts b/examples/zero-configuration/src/index.ts new file mode 100644 index 000000000..97eb0c911 --- /dev/null +++ b/examples/zero-configuration/src/index.ts @@ -0,0 +1 @@ +console.log(123); diff --git a/examples/zero-configuration/tsconfig.json b/examples/zero-configuration/tsconfig.json new file mode 100644 index 000000000..d38eab65e --- /dev/null +++ b/examples/zero-configuration/tsconfig.json @@ -0,0 +1,6 @@ +{ + "compilerOptions": { + "strict": true + }, + "include": ["src/**/*"] +} diff --git a/packages/core/src/config.ts b/packages/core/src/config.ts index 952165746..a61fef8b4 100644 --- a/packages/core/src/config.ts +++ b/packages/core/src/config.ts @@ -14,7 +14,7 @@ import type { AutoExternal, Format, LibConfig, - PkgJson, + PackageJson, RslibConfig, RslibConfigAsyncFn, RslibConfigExport, @@ -25,6 +25,7 @@ import { getDefaultExtension } from './utils/extension'; import { calcLongestCommonPath, color, + getExportEntries, isObject, nodeBuiltInModules, readPackageJson, @@ -48,7 +49,10 @@ const findConfig = (basePath: string): string | undefined => { return DEFAULT_EXTENSIONS.map((ext) => basePath + ext).find(fs.existsSync); }; -const resolveConfigPath = (root: string, customConfig?: string): string => { +const resolveConfigPath = ( + root: string, + customConfig?: string, +): string | null => { if (customConfig) { const customConfigPath = isAbsolute(customConfig) ? customConfig @@ -65,7 +69,7 @@ const resolveConfigPath = (root: string, customConfig?: string): string => { return configFilePath; } - throw new Error(`${DEFAULT_CONFIG_NAME} not found in ${root}`); + return null; }; export async function loadConfig({ @@ -78,18 +82,27 @@ export async function loadConfig({ envMode?: string; }): Promise { const configFilePath = resolveConfigPath(cwd, path); - const { content } = await loadRsbuildConfig({ - cwd: dirname(configFilePath), - path: configFilePath, - envMode, - }); + if (configFilePath) { + const { content } = await loadRsbuildConfig({ + cwd: dirname(configFilePath), + path: configFilePath, + envMode, + }); + + return content as RslibConfig; + } + + const pkgJson = readPackageJson(cwd); + if (pkgJson) { + const exportEntries = getExportEntries(pkgJson); + } - return content as RslibConfig; + return {} as RslibConfig; } export const composeAutoExternalConfig = (options: { autoExternal: AutoExternal; - pkgJson?: PkgJson; + pkgJson?: PackageJson; userExternals?: NonNullable['externals']; }): RsbuildConfig => { const { autoExternal, pkgJson, userExternals } = options; @@ -242,7 +255,7 @@ const composeFormatConfig = (format: Format): RsbuildConfig => { const composeAutoExtensionConfig = ( config: LibConfig, autoExtension: boolean, - pkgJson?: PkgJson, + pkgJson?: PackageJson, ): { config: RsbuildConfig; jsExtension: string; diff --git a/packages/core/src/types/config/index.ts b/packages/core/src/types/config/index.ts index df08a54f6..113269638 100644 --- a/packages/core/src/types/config/index.ts +++ b/packages/core/src/types/config/index.ts @@ -2,6 +2,14 @@ import type { RsbuildConfig } from '@rsbuild/core'; export type Format = 'esm' | 'cjs' | 'umd'; +export type PackageType = 'module' | 'commonjs'; + +export type ExportEntry = { + outputPath: string; + type: PackageType | 'types'; + from: string; +}; + export type EcmaScriptVersion = | 'esnext' | 'es5' diff --git a/packages/core/src/types/external/typeFest.ts b/packages/core/src/types/external/typeFest.ts new file mode 100644 index 000000000..f1b2acb5c --- /dev/null +++ b/packages/core/src/types/external/typeFest.ts @@ -0,0 +1,239 @@ +/** + * The following code is modified based on + * https://github.com/sindresorhus/type-fest/blob/986fab/source/package-json.d.ts + * + * MIT OR CC0-1.0 Licensed + * https://github.com/sindresorhus/type-fest/blob/main/license-cc0 + */ + +/** + * Matches a JSON object. + * + * This type can be useful to enforce some input to be JSON-compatible or as a super-type to be extended from. Don't use this as a direct return type as the user would have to double-cast it: `jsonObject as unknown as CustomResponse`. Instead, you could extend your CustomResponse type from it to ensure your type only uses JSON-compatible types: `interface CustomResponse extends JsonObject { … }`. + * + * @category JSON + */ +type JsonObject = { [Key in string]: JsonValue } & { + [Key in string]?: JsonValue | undefined; +}; + +/** + * Matches a JSON array. + * + * @category JSON + */ +type JsonArray = JsonValue[] | readonly JsonValue[]; + +/** + * Matches any valid JSON primitive value. + * + * @category JSON + */ +type JsonPrimitive = string | number | boolean | null; + +/** + * Matches any valid JSON value. + * + * @category JSON + */ +type JsonValue = JsonPrimitive | JsonObject | JsonArray; + +type Scripts = Partial>; + +type Dependency = Partial>; + +/** + * A mapping of conditions and the paths to which they resolve. + */ +type ExportConditions = { + // eslint-disable-line @typescript-eslint/consistent-indexed-object-style + [condition: string]: Exports; +}; + +/** + * Entry points of a module, optionally with conditions and subpath exports. + */ +type Exports = + | null + | string + | Array + | ExportConditions; + +/** + * Import map entries of a module, optionally with conditions and subpath imports. + */ +type Imports = { + [key: `#${string}`]: Exports; +}; + +interface NonStandardEntryPoints { + /** + An ECMAScript module ID that is the primary entry point to the program. + */ + module?: string; + + /** + Denote which files in your project are "pure" and therefore safe for Webpack to prune if unused. + + [Read more.](https://webpack.js.org/guides/tree-shaking/) + */ + sideEffects?: boolean | string[]; +} + +/** + * Type for [npm's `package.json` file](https://docs.npmjs.com/creating-a-package-json-file). Containing standard npm properties. + */ +interface PackageJsonStandard { + /** + The name of the package. + */ + name?: string; + + /** + Package version, parseable by [`node-semver`](https://github.com/npm/node-semver). + */ + version?: string; + + /** + Package description, listed in `npm search`. + */ + description?: string; + + /** + Keywords associated with package, listed in `npm search`. + */ + keywords?: string[]; + + /** + The licenses for the package. + */ + licenses?: Array<{ + type?: string; + url?: string; + }>; + + /** + The files included in the package. + */ + files?: string[]; + + /** + Resolution algorithm for importing ".js" files from the package's scope. + + [Read more.](https://nodejs.org/api/esm.html#esm_package_json_type_field) + */ + type?: 'module' | 'commonjs'; + + /** + The module ID that is the primary entry point to the program. + */ + main?: string; + + /** + Subpath exports to define entry points of the package. + + [Read more.](https://nodejs.org/api/packages.html#subpath-exports) + */ + exports?: Exports; + + /** + Subpath imports to define internal package import maps that only apply to import specifiers from within the package itself. + + [Read more.](https://nodejs.org/api/packages.html#subpath-imports) + */ + imports?: Imports; + + /** + The executable files that should be installed into the `PATH`. + */ + bin?: string | Partial>; + + /** + Script commands that are run at various times in the lifecycle of the package. The key is the lifecycle event, and the value is the command to run at that point. + */ + scripts?: Scripts; + + /** + Is used to set configuration parameters used in package scripts that persist across upgrades. + */ + config?: JsonObject; + + /** + The dependencies of the package. + */ + dependencies?: Dependency; + + /** + Additional tooling dependencies that are not required for the package to work. Usually test, build, or documentation tooling. + */ + devDependencies?: Dependency; + + /** + Dependencies that will usually be required by the package user directly or via another dependency. + */ + peerDependencies?: Dependency; + + /** + Engines that this package runs on. + */ + engines?: { + [EngineName in 'npm' | 'node' | string]?: string; + }; + + /** + @deprecated + */ + engineStrict?: boolean; + + /** + If set to `true`, a warning will be shown if package is installed locally. Useful if the package is primarily a command-line application that should be installed globally. + + @deprecated + */ + preferGlobal?: boolean; + + /** + If set to `true`, then npm will refuse to publish it. + */ + private?: boolean; + + /** + A set of config values that will be used at publish-time. It's especially handy to set the tag, registry or access, to ensure that a given package is not tagged with 'latest', published to the global public registry or that a scoped module is private by default. + */ + publishConfig?: PublishConfig; +} + +type PublishConfig = { + /** + Additional, less common properties from the [npm docs on `publishConfig`](https://docs.npmjs.com/cli/v7/configuring-npm/package-json#publishconfig). + */ + [additionalProperties: string]: JsonValue | undefined; + + /** + When publishing scoped packages, the access level defaults to restricted. If you want your scoped package to be publicly viewable (and installable) set `--access=public`. The only valid values for access are public and restricted. Unscoped packages always have an access level of public. + */ + access?: 'public' | 'restricted'; + + /** + The base URL of the npm registry. + + Default: `'https://registry.npmjs.org/'` + */ + registry?: string; + + /** + The tag to publish the package under. + + Default: `'latest'` + */ + tag?: string; +}; + +/** + * Type for [npm's `package.json` file](https://docs.npmjs.com/creating-a-package-json-file). Also includes types for fields used by other popular projects, like TypeScript and Yarn. + * + * @category File + */ +export type PackageJson = JsonObject & + PackageJsonStandard & + NonStandardEntryPoints; diff --git a/packages/core/src/types/index.ts b/packages/core/src/types/index.ts index 235e5fdbc..ad28bd987 100644 --- a/packages/core/src/types/index.ts +++ b/packages/core/src/types/index.ts @@ -1,2 +1,2 @@ export type * from './config'; -export type * from './utils'; +export type * from './external/typeFest'; diff --git a/packages/core/src/types/utils.ts b/packages/core/src/types/utils.ts deleted file mode 100644 index 8b3d31293..000000000 --- a/packages/core/src/types/utils.ts +++ /dev/null @@ -1,6 +0,0 @@ -export type PkgJson = { - dependencies?: Record; - peerDependencies?: Record; - devDependencies?: Record; - [key: string]: unknown; -}; diff --git a/packages/core/src/utils/extension.ts b/packages/core/src/utils/extension.ts index 7d514a9e9..681865436 100644 --- a/packages/core/src/utils/extension.ts +++ b/packages/core/src/utils/extension.ts @@ -1,9 +1,9 @@ -import type { Format, PkgJson } from '../types'; +import type { Format, PackageJson } from '../types'; import { logger } from './logger'; export const getDefaultExtension = (options: { format: Format; - pkgJson?: PkgJson; + pkgJson?: PackageJson; autoExtension: boolean; }): { jsExtension: string; diff --git a/packages/core/src/utils/helper.ts b/packages/core/src/utils/helper.ts index 387e20123..9bc787625 100644 --- a/packages/core/src/utils/helper.ts +++ b/packages/core/src/utils/helper.ts @@ -2,7 +2,7 @@ import fs from 'node:fs'; import fsP from 'node:fs/promises'; import path from 'node:path'; import color from 'picocolors'; -import type { PkgJson } from '../types'; +import type { ExportEntry, PackageJson, PackageType } from '../types'; import { logger } from './logger'; /** @@ -107,7 +107,7 @@ export async function calcLongestCommonPath( return lca; } -export const readPackageJson = (rootPath: string): undefined | PkgJson => { +export const readPackageJson = (rootPath: string): undefined | PackageJson => { const pkgJsonPath = path.join(rootPath, './package.json'); if (!fs.existsSync(pkgJsonPath)) { @@ -123,6 +123,56 @@ export const readPackageJson = (rootPath: string): undefined | PkgJson => { } }; +export const getExportEntries = (pkgJson: PackageJson): ExportEntry[] => { + const exportEntriesMap: Record = {}; + const packageType = pkgJson.type ?? 'commonjs'; + + const getFileType = (filePath: string): PackageType => { + if (filePath.endsWith('.mjs')) { + return 'module'; + } + + if (filePath.endsWith('.cjs')) { + return 'commonjs'; + } + + return packageType; + }; + + const addExportPath = ( + exportPathsMap: Record, + exportEntry: any, + ) => { + exportEntry.outputPath = path.normalize(exportEntry.outputPath); + + const { outputPath: exportPath, type } = exportEntry; + + const existingExportPath = exportPathsMap[exportPath]; + if (existingExportPath) { + if (existingExportPath.type !== type) { + throw new Error( + `Conflicting export types "${existingExportPath.type}" & "${type}" found for ${exportPath}`, + ); + } + + Object.assign(existingExportPath, exportEntry); + } else { + exportPathsMap[exportPath] = exportEntry; + } + }; + + if (pkgJson.main) { + const mainPath = pkgJson.main; + addExportPath(exportEntriesMap, { + outputPath: mainPath, + type: getFileType(mainPath), + from: 'main', + }); + } + + return Object.values(exportEntriesMap); +}; + export const isObject = (obj: unknown): obj is Record => Object.prototype.toString.call(obj) === '[object Object]'; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 916a50b2b..cbecf7421 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -145,6 +145,8 @@ importers: e2e/cases/dts/bundle/abort-on-error: {} + e2e/cases/dts/bundle/absolute-entry: {} + e2e/cases/dts/bundle/auto-extension: {} e2e/cases/dts/bundle/basic: {} @@ -187,6 +189,15 @@ importers: specifier: ^18.3.1 version: 18.3.1 + examples/zero-configuration: + devDependencies: + '@rslib/core': + specifier: workspace:* + version: link:../../packages/core + typescript: + specifier: ^5.5.4 + version: 5.5.4 + packages/core: dependencies: '@microsoft/api-extractor':