Skip to content

Commit

Permalink
fix!: remove legacyExports (#1315)
Browse files Browse the repository at this point in the history
  • Loading branch information
stipsan authored Jan 8, 2025
1 parent 259cfb2 commit 36d8155
Show file tree
Hide file tree
Showing 20 changed files with 299 additions and 1,555 deletions.
3 changes: 1 addition & 2 deletions src/node/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,7 @@ export async function build(options: {

const config = await loadConfig({cwd})

const legacyExports = config?.legacyExports ?? false
const pkg = await loadPkgWithReporting({cwd, logger, strict, legacyExports})
const pkg = await loadPkgWithReporting({cwd, logger, strict})

const tsconfig = tsconfigOption || config?.tsconfig || 'tsconfig.json'

Expand Down
3 changes: 1 addition & 2 deletions src/node/check.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,7 @@ export async function check(options: {
const logger = createLogger()

const config = await loadConfig({cwd})
const legacyExports = config?.legacyExports ?? false
const pkg = await loadPkgWithReporting({cwd, logger, strict, legacyExports})
const pkg = await loadPkgWithReporting({cwd, logger, strict})
const tsconfig = tsconfigOption || config?.tsconfig || 'tsconfig.json'
const ctx = await resolveBuildContext({config, cwd, logger, pkg, strict, tsconfig})

Expand Down
5 changes: 2 additions & 3 deletions src/node/core/config/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -255,10 +255,9 @@ export interface PkgConfigOptions {
*/
jsxImportSource?: string
/**
* Build package with support for legacy exports (writes root `<export>.js` files)
* @deprecated - will be removed in the next major version
* @deprecated no longer supported
*/
legacyExports?: boolean
legacyExports?: never
minify?: boolean
/** @alpha */
rollup?: {
Expand Down
12 changes: 2 additions & 10 deletions src/node/core/pkg/loadPkgWithReporting.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,23 +11,15 @@ export async function loadPkgWithReporting(options: {
cwd: string
logger: Logger
strict: boolean
legacyExports: boolean
}): Promise<PackageJSON> {
const {cwd, logger, strict, legacyExports} = options
const {cwd, logger, strict} = options

try {
const pkg = await loadPkg({cwd})
let shouldError = false

if (strict) {
if (legacyExports && pkg.type === 'commonjs') {
shouldError = true
logger.error(
`the \`type\` field in \`./package.json\` shouldn't be "commonjs" when \`legacyExports\` is set to true)`,
)
}

if (!legacyExports && !pkg.type) {
if (!pkg.type) {
shouldError = true
logger.error(
`the \`type\` field in \`./package.json\` must be either "module" or "commonjs")`,
Expand Down
53 changes: 7 additions & 46 deletions src/node/core/pkg/parseExports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import {resolve as resolvePath} from 'node:path'

import type {Logger} from '../../logger'
import type {InferredStrictOptions} from '../../strict'
import {defaultEnding, fileEnding, legacyEnding} from '../../tasks/dts/getTargetPaths'
import {defaultEnding, fileEnding} from '../../tasks/dts/getTargetPaths'
import type {PkgExport} from '../config'
import {isRecord} from '../isRecord'
import {pkgExtMap} from './pkgExt'
Expand All @@ -16,10 +16,9 @@ export function parseExports(options: {
pkg: PackageJSON
strict: boolean
strictOptions: InferredStrictOptions
legacyExports: boolean
logger: Logger
}): (PkgExport & {_path: string})[] {
const {cwd, pkg, strict, strictOptions, legacyExports, logger} = options
const {cwd, pkg, strict, strictOptions, logger} = options
const type = pkg.type || 'commonjs'
const errors: string[] = []

Expand Down Expand Up @@ -72,20 +71,12 @@ export function parseExports(options: {
browserConditions.push(
` "import": ${JSON.stringify(pkg.browser?.[pkg.main].replace(fileEnding, extMap.esm))}`,
)
} else if (legacyExports) {
const browserImport = pkg.main.replace(fileEnding, `.browser${extMap.esm}`)

browserConditions.push(` "import": ${JSON.stringify(browserImport)}`)
}

if (pkg.browser?.[pkg.main]) {
browserConditions.push(
` "require": ${JSON.stringify(pkg.browser[pkg.main].replace(fileEnding, extMap.commonjs))}`,
)
} else if (legacyExports) {
const browserRequire = pkg.main.replace(fileEnding, `.browser${extMap.commonjs}`)

browserConditions.push(` "require": ${JSON.stringify(browserRequire)}`)
}

if (browserConditions.length) {
Expand All @@ -106,11 +97,8 @@ export function parseExports(options: {
` "source": ${JSON.stringify(pkg.source)},`,
// If browser conditions are detected then add them to the suggestion
...(maybeBrowserCondition.length > 0 ? maybeBrowserCondition : []),
// If legacy exports are enabled we suggest the full list of exports, if not we can use the terse version
(legacyExports || type === 'commonjs') &&
` "import": ${JSON.stringify(importExport)},`,
(legacyExports || type === 'module') &&
` "require": ${JSON.stringify(requireExport)},`,
type === 'commonjs' && ` "import": ${JSON.stringify(importExport)},`,
type === 'module' && ` "require": ${JSON.stringify(requireExport)},`,
` "default": ${JSON.stringify(defaultExport)}`,
` },`,
` "./package.json": "./package.json"`,
Expand Down Expand Up @@ -142,8 +130,6 @@ export function parseExports(options: {

const _exports: (PkgExport & {_path: string})[] = []

// @TODO validate typesVersions when legacyExports is true

if (strict && strictOptions.noPackageJsonTypings !== 'off' && 'typings' in pkg) {
report(strictOptions.noPackageJsonTypings, 'package.json: `typings` should be `types`')
}
Expand Down Expand Up @@ -202,18 +188,6 @@ export function parseExports(options: {
if (fallback) {
exp.default = fallback
}

if (legacyExports) {
if (fallback) {
errors.push(
`package.json - \`exports["${exp._path}"].default\` should be set to "${fallback}" when "legacyExports" is true`,
)
} else {
errors.push(
`package.json - \`exports["${exp._path}"].default\` should be specified when "legacyExports" is true`,
)
}
}
}

// Infer the `require` condition based on the `type` and other conditions
Expand All @@ -233,23 +207,10 @@ export function parseExports(options: {
)
}

if (legacyExports) {
const indexLegacyExport = (exportEntry.import || exportEntry.require || '').replace(
/(\.esm)?\.[mc]?js$/,
legacyEnding,
if (exportEntry.import && pkg.module && exportEntry.import !== pkg.module) {
errors.push(
'package.json: mismatch between "module" and "exports.import" These must be equal.',
)

if (indexLegacyExport !== pkg.module) {
errors.push(
`package.json: "module" should be "${indexLegacyExport}" when "legacyExports" is true`,
)
}
} else {
if (exportEntry.import && pkg.module && exportEntry.import !== pkg.module) {
errors.push(
'package.json: mismatch between "module" and "exports.import" These must be equal.',
)
}
}
}

Expand Down
5 changes: 1 addition & 4 deletions src/node/core/pkg/pkgExt.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import {cjsEnding, defaultEnding, legacyEnding, mjsEnding} from '../../tasks/dts/getTargetPaths'
import {cjsEnding, defaultEnding, mjsEnding} from '../../tasks/dts/getTargetPaths'

/** @internal */
export interface PkgExtMap {
commonjs: {commonjs: string; esm: string}
module: {commonjs: string; esm: string}
legacy: string
}

/** @internal */
Expand All @@ -20,6 +19,4 @@ export const pkgExtMap = {
commonjs: cjsEnding,
esm: defaultEnding,
},
// package.config.legacyExports: true
legacy: legacyEnding,
} satisfies PkgExtMap
1 change: 0 additions & 1 deletion src/node/core/pkg/validateExports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ export function validateExports(

const errors: string[] = []

// @TODO validate that no exports declare the legacy exports
for (const exp of _exports) {
if (exp.require && !exp.require.endsWith(ext.commonjs)) {
errors.push(
Expand Down
1 change: 0 additions & 1 deletion src/node/resolveBuildContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,6 @@ export async function resolveBuildContext(options: {
cwd,
pkg,
strict,
legacyExports: config?.legacyExports ?? false,
strictOptions,
logger,
}).reduce<PkgExports>((acc, x) => {
Expand Down
66 changes: 4 additions & 62 deletions src/node/resolveBuildTasks.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import fs from 'node:fs'
import path from 'node:path'

import type {BuildContext, PkgExport, PkgFormat, PkgRuntime} from './core'
import type {BuildTask, DtsTask, RollupLegacyTask, RollupTask, RollupTaskEntry} from './tasks'
import {fileEnding, getTargetPaths, legacyEnding} from './tasks/dts/getTargetPaths'
import type {BuildTask, DtsTask, RollupTask, RollupTaskEntry} from './tasks'
import {getTargetPaths} from './tasks/dts/getTargetPaths'

/** @internal */
export function resolveBuildTasks(ctx: BuildContext): BuildTask[] {
const {config, cwd, pkg, target} = ctx
const {config, pkg, target} = ctx

const bundles = config?.bundles || []

Expand All @@ -23,7 +22,6 @@ export function resolveBuildTasks(ctx: BuildContext): BuildTask[] {
}

const rollupTasks: Record<string, RollupTask> = {}
const rollupLegacyTasks: Record<string, RollupLegacyTask> = {}

function addRollupTaskEntry(format: PkgFormat, runtime: PkgRuntime, entry: RollupTaskEntry) {
const buildId = `${format}:${runtime}`
Expand All @@ -42,24 +40,6 @@ export function resolveBuildTasks(ctx: BuildContext): BuildTask[] {
}
}

function addRollupLegacyTaskEntry(runtime: PkgRuntime, entry: RollupTaskEntry) {
const buildId = `esm:${runtime}`

if (rollupLegacyTasks[buildId]) {
rollupLegacyTasks[buildId].entries.push(entry)
} else {
rollupLegacyTasks[buildId] = {
type: 'build:legacy',
buildId,
entries: [entry],
runtime,
format: 'esm',
// @TODO set a different target here that is compatible with legacy bundlers and testing tools like brownfield jest
target: target[runtime],
}
}
}

// Parse `dts` tasks
for (const exp of exports) {
const importId = path.join(pkg.name, exp._path)
Expand Down Expand Up @@ -168,25 +148,6 @@ export function resolveBuildTasks(ctx: BuildContext): BuildTask[] {
})
}

// Create rollup bundles that legacy export files will re-export
if (config?.legacyExports) {
for (const exp of exports) {
const runtime = exp.browser?.import ? 'browser' : ctx.runtime
const output = exp.browser?.import || exp.import

if (!output) continue

// Change the suffix to what the legacy exports will use
const legacyOutput = output.replace(fileEnding, legacyEnding)

addRollupLegacyTaskEntry(runtime, {
path: exp._path,
source: exp.browser?.source || exp.source,
output: legacyOutput,
})
}
}

for (const bundle of bundles) {
const idx = bundles.indexOf(bundle)

Expand All @@ -207,26 +168,7 @@ export function resolveBuildTasks(ctx: BuildContext): BuildTask[] {
}
}

tasks.push(...Object.values(rollupTasks), ...Object.values(rollupLegacyTasks))

// Write legacy exports files
if (config?.legacyExports) {
for (const exp of exports) {
if (exp._exported && exp._path !== '.') {
const output = (exp.browser?.import || exp.import || '').replace(fileEnding, legacyEnding)
const relativeTargetPath = output.replace(/\.[^/.]+$/, '')

if (relativeTargetPath) {
fs.writeFileSync(
path.resolve(cwd, `${exp._path}.js`),
['// AUTO-GENERATED – DO NOT EDIT', `export * from '${relativeTargetPath}'`, ''].join(
'\n',
),
)
}
}
}
}
tasks.push(...Object.values(rollupTasks))
}

return tasks
Expand Down
24 changes: 1 addition & 23 deletions src/node/resolveWatchTasks.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import fs from 'node:fs'
import path from 'node:path'

import type {BuildContext, PkgExport, PkgFormat, PkgRuntime} from './core'
Expand All @@ -7,7 +6,7 @@ import {getTargetPaths} from './tasks/dts/getTargetPaths'

/** @internal */
export function resolveWatchTasks(ctx: BuildContext): WatchTask[] {
const {config, cwd, pkg, target} = ctx
const {pkg, target} = ctx
const tasks: WatchTask[] = []

const exports = Object.entries(ctx.exports || {}).map(
Expand Down Expand Up @@ -128,26 +127,5 @@ export function resolveWatchTasks(ctx: BuildContext): WatchTask[] {

tasks.push(...Object.values(rollupTasks))

// Write legacy exports files
if (config?.legacyExports) {
for (const exp of exports) {
if (exp._exported && exp._path !== '.') {
const relativeTargetPath = (exp.browser?.import || exp.import || '').replace(
/\.[^/.]+$/,
'',
)

if (relativeTargetPath) {
fs.writeFileSync(
path.resolve(cwd, `${exp._path}.js`),
[`// AUTO-GENERATED – DO NOT EDIT`, `export * from '${relativeTargetPath}'`, ``].join(
'\n',
),
)
}
}
}
}

return tasks
}
2 changes: 0 additions & 2 deletions src/node/tasks/dts/getTargetPaths.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@ export const dtsEnding = '.d.ts' as const
/** @internal */
export const defaultEnding = '.js' as const
/** @internal */
export const legacyEnding = `.esm${defaultEnding}` as const
/** @internal */
export const mjsEnding = '.mjs' as const
/** @internal */
export const cjsEnding = '.cjs' as const
Expand Down
3 changes: 1 addition & 2 deletions src/node/tasks/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {dtsTask, dtsWatchTask} from './dts'
import {rollupLegacyTask, rollupTask, rollupWatchTask} from './rollup'
import {rollupTask, rollupWatchTask} from './rollup'
import type {BuildTaskHandlers, WatchTaskHandlers} from './types'

export * from './dts'
Expand All @@ -10,7 +10,6 @@ export * from './types'
export const buildTaskHandlers: BuildTaskHandlers = {
'build:dts': dtsTask,
'build:js': rollupTask,
'build:legacy': rollupLegacyTask,
}

/** @internal */
Expand Down
1 change: 0 additions & 1 deletion src/node/tasks/rollup/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,2 @@
export * from './rollupLegacyTask'
export * from './rollupTask'
export * from './rollupWatchTask'
Loading

0 comments on commit 36d8155

Please sign in to comment.