fix(nuxt): add types for webpack/vite environments (#20749)

This commit is contained in:
Daniel Roe 2023-05-15 17:17:39 +01:00 committed by GitHub
parent 33e2bd3dc0
commit 038c84c4b1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
10 changed files with 48 additions and 3 deletions

View File

@ -304,6 +304,29 @@ async function initNuxt (nuxt: Nuxt) {
addPlugin(resolve(nuxt.options.appDir, 'plugins/preload.server'))
}
const envMap = {
// defaults from `builder` based on package name
'@nuxt/vite-builder': 'vite/client',
'@nuxt/webpack-builder': 'webpack/module',
// simpler overrides from `typescript.builder` for better DX
vite: 'vite/client',
webpack: 'webpack/module',
// default 'merged' builder environment for module authors
shared: '@nuxt/schema/builder-env'
}
nuxt.hook('prepare:types', ({ references }) => {
// Disable entirely if `typescript.builder` is false
if (nuxt.options.typescript.builder === false) { return }
const overrideEnv = nuxt.options.typescript.builder && envMap[nuxt.options.typescript.builder]
// If there's no override, infer based on builder. If a custom builder is provided, we disable shared types
const defaultEnv = typeof nuxt.options.builder === 'string' ? envMap[nuxt.options.builder] : false
const types = overrideEnv || defaultEnv
if (types) { references.push({ types }) }
})
// Add nuxt app debugger
if (nuxt.options.debug) {
addPlugin(resolve(nuxt.options.appDir, 'plugins/debug'))

View File

@ -16,6 +16,7 @@ export default defineBuildConfig({
}
},
'src/index',
'src/builder-env'
],
externals: [
// Type imports

1
packages/schema/builder-env.d.ts vendored Normal file
View File

@ -0,0 +1 @@
export * from './dist/env'

View File

@ -11,11 +11,16 @@
"import": "./dist/index.mjs",
"require": "./dist/index.mjs"
},
"./builder-env": {
"types": "./dist/builder-env.d.ts",
"import": "./dist/builder-env.mjs"
},
"./package.json": "./package.json"
},
"files": [
"dist",
"schema"
"schema",
"env.d.ts"
],
"scripts": {
"prepack": "unbuild"

View File

@ -0,0 +1,3 @@
import './types/builder-env'
export const builders = ['vite', 'webpack']

View File

@ -13,6 +13,20 @@ export default defineUntypedSchema({
*/
strict: true,
/**
* Which builder types to include for your project.
*
* By default Nuxt infers this based on your `builder` option (defaulting to 'vite') but you can either turn off
* builder environment types (with `false`) to handle this fully yourself, or opt for a 'shared' option.
*
* The 'shared' option is advised for module authors, who will want to support multiple possible builders.
*
* @type {'vite' | 'webpack' | 'shared' | false | undefined}
*/
builder: {
$resolve: async (val, get) => val ?? null
},
/**
* Include parent workspace in the Nuxt project. Mostly useful for themes and module authors.
*/

View File

@ -1,7 +1,5 @@
// Types
import './types/global'
export * from './types/compatibility'
export * from './types/components'
export * from './types/config'