Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: show error when accessing variables not exposed in CJS build #18649

Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 34 additions & 3 deletions packages/vite/index.cjs
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
const description =
' See https://vite.dev/guide/troubleshooting.html#vite-cjs-node-api-deprecated for more details.'

warnCjsUsage()

// type utils
Expand All @@ -17,12 +20,42 @@ const asyncFunctions = [
'formatPostcssSourceMap',
'loadConfigFromFile',
'preprocessCSS',
'createBuilder',
]
asyncFunctions.forEach((name) => {
module.exports[name] = (...args) =>
import('./dist/node/index.js').then((i) => i[name](...args))
})

// variables and sync functions that cannot be used from cjs build
const disallowedVariables = [
// was not exposed in cjs from the beggining
sapphi-red marked this conversation as resolved.
Show resolved Hide resolved
'parseAst',
'buildErrorMessage',
'sortUserPlugins',
// Environment API related variables that are too big to include in the cjs build
'DevEnvironment',
'BuildEnvironment',
'createIdResolver',
'createRunnableDevEnvironment',
// can be redirected from ESM, but doesn't make sense as it's Environment API related
'fetchModule',
'moduleRunnerTransform',
// can be exposed, but doesn't make sense as it's Environment API related
'createServerHotChannel',
'createServerModuleRunner',
'isRunnableDevEnvironment',
]
disallowedVariables.forEach((name) => {
Object.defineProperty(module.exports, name, {
get() {
throw new Error(
`${name} is not available in the CJS build. ` + description,
sapphi-red marked this conversation as resolved.
Show resolved Hide resolved
)
},
})
})

function warnCjsUsage() {
if (process.env.VITE_CJS_IGNORE_WARNING) return
const logLevelIndex = process.argv.findIndex((arg) =>
Expand All @@ -39,9 +72,7 @@ function warnCjsUsage() {
}
const yellow = (str) => `\u001b[33m${str}\u001b[39m`
console.warn(
yellow(
`The CJS build of Vite's Node API is deprecated. See https://vite.dev/guide/troubleshooting.html#vite-cjs-node-api-deprecated for more details.`,
),
yellow("The CJS build of Vite's Node API is deprecated." + description),
)
if (process.env.VITE_CJS_TRACE) {
const e = {}
Expand Down
Loading