Skip to content

Commit bd42eda

Browse files
Gugustinettesxzz
andauthored
feat: warn user if config includes cjs format (#403)
Co-authored-by: Kevin Deng <[email protected]>
1 parent d0e316f commit bd42eda

File tree

3 files changed

+33
-2
lines changed

3 files changed

+33
-2
lines changed

src/features/cjs.ts

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import coerce from 'semver/functions/coerce.js'
2+
import satisfies from 'semver/functions/satisfies.js'
3+
import type { ResolvedOptions } from '../options'
4+
5+
/**
6+
* If the config includes the `cjs` format and
7+
* one of its target >= node 23.0.0 / 22.12.0,
8+
* warn the user about the deprecation of CommonJS.
9+
*/
10+
export function warnLegacyCJS(config: ResolvedOptions): void {
11+
if (!config.format.includes('cjs') || !config.target) {
12+
return
13+
}
14+
15+
const legacy = config.target.some((t) => {
16+
const version = coerce(t.split('node')[1])
17+
return version && satisfies(version, '>=23.0.0 || >=22.12.0')
18+
})
19+
20+
if (legacy) {
21+
config.logger.warnOnce(
22+
'We recommend using the ESM format instead of CommonJS.\n' +
23+
'The ESM format is compatible with modern platforms and runtimes, ' +
24+
'and most new libraries are now distributed only in ESM format.\n' +
25+
'Learn more at https://nodejs.org/en/learn/modules/publishing-a-package#how-did-we-get-here',
26+
)
27+
}
28+
}

src/index.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import {
1111
import { exec } from 'tinyexec'
1212
import treeKill from 'tree-kill'
1313
import { attw } from './features/attw'
14+
import { warnLegacyCJS } from './features/cjs'
1415
import { cleanOutDir } from './features/clean'
1516
import { copy } from './features/copy'
1617
import { writeExports, type TsdownChunks } from './features/exports'
@@ -103,6 +104,8 @@ export async function buildSingle(
103104

104105
const { hooks, context } = await createHooks(config)
105106

107+
warnLegacyCJS(config)
108+
106109
await rebuild(true)
107110
if (watch) {
108111
return () => rebuild()

src/utils/logger.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,8 @@ function format(msgs: any[]) {
3030
return msgs.filter((arg) => arg !== undefined && arg !== false).join(' ')
3131
}
3232

33+
const warnedMessages = new Set<string>()
34+
3335
export function createLogger(
3436
level: LogLevel = 'info',
3537
{ customLogger, console = globalThis.console }: LoggerOptions = {},
@@ -46,8 +48,6 @@ export function createLogger(
4648
console[method](msg)
4749
}
4850

49-
const warnedMessages = new Set<string>()
50-
5151
const logger: Logger = {
5252
level,
5353

0 commit comments

Comments
 (0)