refactor(nuxt)!: rename autoImports to imports (#6864)

Co-authored-by: Pooya Parsa <pooya@pi0.io>
This commit is contained in:
Anthony Fu 2022-08-23 22:22:11 +08:00 committed by GitHub
parent 45f39be4fa
commit fd94351ee9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
16 changed files with 77 additions and 44 deletions

View File

@ -98,7 +98,7 @@ export { utils } from './nested/utils.ts'
```ts [nuxt.config.ts] ```ts [nuxt.config.ts]
export default defineNuxtConfig({ export default defineNuxtConfig({
autoImports: { imports: {
dirs: [ dirs: [
// Scan top-level modules // Scan top-level modules
'composables', 'composables',

View File

@ -278,7 +278,7 @@ export default defineNuxtConfig({
// scriptSetup: false, // scriptSetup: false,
// Disable composables auto importing // Disable composables auto importing
// autoImports: false, // imports: false,
// Do not warn about module incompatibilities // Do not warn about module incompatibilities
// constraints: false // constraints: false

View File

@ -1,7 +1,7 @@
import { defineNuxtConfig } from 'nuxt' import { defineNuxtConfig } from 'nuxt'
export default defineNuxtConfig({ export default defineNuxtConfig({
autoImports: { imports: {
dirs: ['utils'] dirs: ['utils']
}, },
publicRuntimeConfig: { publicRuntimeConfig: {

View File

@ -5,17 +5,17 @@ import { assertNuxtCompatibility } from './compatibility'
export function addAutoImport (imports: Import | Import[]) { export function addAutoImport (imports: Import | Import[]) {
assertNuxtCompatibility({ bridge: true }) assertNuxtCompatibility({ bridge: true })
useNuxt().hook('autoImports:extend', (autoImports) => { useNuxt().hook('imports:extend', (_imports) => {
autoImports.push(...(Array.isArray(imports) ? imports : [imports])) _imports.push(...(Array.isArray(imports) ? imports : [imports]))
}) })
} }
export function addAutoImportDir (_autoImportDirs: string | string[]) { export function addAutoImportDir (dirs: string | string[]) {
assertNuxtCompatibility({ bridge: true }) assertNuxtCompatibility({ bridge: true })
useNuxt().hook('autoImports:dirs', (autoImportDirs: string[]) => { useNuxt().hook('imports:dirs', (_dirs: string[]) => {
for (const dir of (Array.isArray(_autoImportDirs) ? _autoImportDirs : [_autoImportDirs])) { for (const dir of (Array.isArray(dirs) ? dirs : [dirs])) {
autoImportDirs.push(dir) _dirs.push(dir)
} }
}) })
} }

View File

@ -48,7 +48,7 @@
"globby": "^13.1.2", "globby": "^13.1.2",
"h3": "^0.7.15", "h3": "^0.7.15",
"hash-sum": "^2.0.0", "hash-sum": "^2.0.0",
"hookable": "^5.1.1", "hookable": "^5.1.2",
"knitwork": "^0.1.2", "knitwork": "^0.1.2",
"magic-string": "^0.26.2", "magic-string": "^0.26.2",
"mlly": "^0.5.14", "mlly": "^0.5.14",

View File

@ -8,7 +8,7 @@ import escapeRE from 'escape-string-regexp'
import pagesModule from '../pages/module' import pagesModule from '../pages/module'
import metaModule from '../head/module' import metaModule from '../head/module'
import componentsModule from '../components/module' import componentsModule from '../components/module'
import autoImportsModule from '../auto-imports/module' import importsModule from '../imports/module'
/* eslint-enable */ /* eslint-enable */
import { distDir, pkgDir } from '../dirs' import { distDir, pkgDir } from '../dirs'
import { version } from '../../package.json' import { version } from '../../package.json'
@ -162,7 +162,7 @@ export async function loadNuxt (opts: LoadNuxtOptions): Promise<Nuxt> {
options.appDir = options.alias['#app'] = resolve(distDir, 'app') options.appDir = options.alias['#app'] = resolve(distDir, 'app')
options._majorVersion = 3 options._majorVersion = 3
options._modules.push(pagesModule, metaModule, componentsModule) options._modules.push(pagesModule, metaModule, componentsModule)
options._modules.push([autoImportsModule, { options._modules.push([importsModule, {
transform: { transform: {
include: options._layers include: options._layers
.filter(i => i.cwd && i.cwd.includes('node_modules')) .filter(i => i.cwd && i.cwd.includes('node_modules'))

View File

@ -110,7 +110,7 @@ export { }
} }
} }
const adHocModules = ['router', 'pages', 'auto-imports', 'meta', 'components'] const adHocModules = ['router', 'pages', 'imports', 'meta', 'components']
export const schemaTemplate: NuxtTemplate<TemplateContext> = { export const schemaTemplate: NuxtTemplate<TemplateContext> = {
filename: 'types/schema.d.ts', filename: 'types/schema.d.ts',
getContents: ({ nuxt }) => { getContents: ({ nuxt }) => {

View File

@ -1,14 +1,15 @@
import { addVitePlugin, addWebpackPlugin, defineNuxtModule, addTemplate, resolveAlias, useNuxt, addPluginTemplate, logger } from '@nuxt/kit' import { addVitePlugin, addWebpackPlugin, defineNuxtModule, addTemplate, resolveAlias, useNuxt, addPluginTemplate, logger } from '@nuxt/kit'
import { isAbsolute, join, relative, resolve, normalize } from 'pathe' import { isAbsolute, join, relative, resolve, normalize } from 'pathe'
import { createUnimport, Import, scanDirExports, toImports, Unimport } from 'unimport' import { createUnimport, Import, scanDirExports, toImports, Unimport } from 'unimport'
import { AutoImportsOptions, ImportPresetWithDeprecation } from '@nuxt/schema' import { ImportsOptions, ImportPresetWithDeprecation } from '@nuxt/schema'
import defu from 'defu'
import { TransformPlugin } from './transform' import { TransformPlugin } from './transform'
import { defaultPresets } from './presets' import { defaultPresets } from './presets'
export default defineNuxtModule<Partial<AutoImportsOptions>>({ export default defineNuxtModule<Partial<ImportsOptions>>({
meta: { meta: {
name: 'auto-imports', name: 'imports',
configKey: 'autoImports' configKey: 'imports'
}, },
defaults: { defaults: {
presets: defaultPresets, presets: defaultPresets,
@ -21,13 +22,28 @@ export default defineNuxtModule<Partial<AutoImportsOptions>>({
} }
}, },
async setup (options, nuxt) { async setup (options, nuxt) {
// TODO: remove deprecation warning
// @ts-ignore
if (nuxt.options.autoImports) {
logger.warn('`autoImports` config is deprecated, use `imports` instead.')
// @ts-ignore
options = defu(nuxt.options.autoImports, options)
}
// @ts-expect-error
nuxt.hooks.deprecateHooks({
'autoImports:sources': { to: 'imports:sources' },
'autoImports:dirs': { to: 'imports:dirs' },
'autoImports:extend': { to: 'imports:extend' }
})
// Allow modules extending sources // Allow modules extending sources
await nuxt.callHook('autoImports:sources', options.presets as ImportPresetWithDeprecation[]) await nuxt.callHook('imports:sources', options.presets as ImportPresetWithDeprecation[])
options.presets?.forEach((i: ImportPresetWithDeprecation | string) => { options.presets?.forEach((i: ImportPresetWithDeprecation | string) => {
if (typeof i !== 'string' && i.names && !i.imports) { if (typeof i !== 'string' && i.names && !i.imports) {
i.imports = i.names i.imports = i.names
logger.warn('auto-imports: presets.names is deprecated, use presets.imports instead') logger.warn('imports: presets.names is deprecated, use presets.imports instead')
} }
}) })
@ -48,7 +64,7 @@ export default defineNuxtModule<Partial<AutoImportsOptions>>({
let composablesDirs: string[] = [] let composablesDirs: string[] = []
for (const layer of nuxt.options._layers) { for (const layer of nuxt.options._layers) {
composablesDirs.push(resolve(layer.config.srcDir, 'composables')) composablesDirs.push(resolve(layer.config.srcDir, 'composables'))
for (const dir of (layer.config.autoImports?.dirs ?? [])) { for (const dir of (layer.config.imports?.dirs ?? [])) {
if (!dir) { if (!dir) {
continue continue
} }
@ -56,13 +72,13 @@ export default defineNuxtModule<Partial<AutoImportsOptions>>({
} }
} }
await nuxt.callHook('autoImports:dirs', composablesDirs) await nuxt.callHook('imports:dirs', composablesDirs)
composablesDirs = composablesDirs.map(dir => normalize(dir)) composablesDirs = composablesDirs.map(dir => normalize(dir))
// Support for importing from '#imports' // Support for importing from '#imports'
addTemplate({ addTemplate({
filename: 'imports.mjs', filename: 'imports.mjs',
getContents: () => ctx.toExports() + '\nif (process.dev) { console.warn("[nuxt] `#imports` should be transformed with real imports. There seems to be something wrong with the auto-imports plugin.") }' getContents: () => ctx.toExports() + '\nif (process.dev) { console.warn("[nuxt] `#imports` should be transformed with real imports. There seems to be something wrong with the imports plugin.") }'
}) })
nuxt.options.alias['#imports'] = join(nuxt.options.buildDir, 'imports') nuxt.options.alias['#imports'] = join(nuxt.options.buildDir, 'imports')
@ -71,7 +87,7 @@ export default defineNuxtModule<Partial<AutoImportsOptions>>({
if (nuxt.options.dev && options.global) { if (nuxt.options.dev && options.global) {
// Add all imports to globalThis in development mode // Add all imports to globalThis in development mode
addPluginTemplate({ addPluginTemplate({
filename: 'auto-imports.mjs', filename: 'imports.mjs',
getContents: () => { getContents: () => {
const imports = ctx.getImports() const imports = ctx.getImports()
const importStatement = toImports(imports) const importStatement = toImports(imports)
@ -85,24 +101,24 @@ export default defineNuxtModule<Partial<AutoImportsOptions>>({
addWebpackPlugin(TransformPlugin.webpack({ ctx, options, sourcemap: nuxt.options.sourcemap })) addWebpackPlugin(TransformPlugin.webpack({ ctx, options, sourcemap: nuxt.options.sourcemap }))
} }
const regenerateAutoImports = async () => { const regenerateImports = async () => {
ctx.clearDynamicImports() ctx.clearDynamicImports()
await ctx.modifyDynamicImports(async (imports) => { await ctx.modifyDynamicImports(async (imports) => {
// Scan composables/ // Scan composables/
imports.push(...await scanDirExports(composablesDirs)) imports.push(...await scanDirExports(composablesDirs))
// Modules extending // Modules extending
await nuxt.callHook('autoImports:extend', imports) await nuxt.callHook('imports:extend', imports)
}) })
} }
await regenerateAutoImports() await regenerateImports()
// Generate types // Generate types
addDeclarationTemplates(ctx) addDeclarationTemplates(ctx)
// Add generated types to `nuxt.d.ts` // Add generated types to `nuxt.d.ts`
nuxt.hook('prepare:types', ({ references }) => { nuxt.hook('prepare:types', ({ references }) => {
references.push({ path: resolve(nuxt.options.buildDir, 'types/auto-imports.d.ts') }) references.push({ path: resolve(nuxt.options.buildDir, 'types/imports.d.ts') })
references.push({ path: resolve(nuxt.options.buildDir, 'imports.d.ts') }) references.push({ path: resolve(nuxt.options.buildDir, 'imports.d.ts') })
}) })
@ -115,7 +131,7 @@ export default defineNuxtModule<Partial<AutoImportsOptions>>({
}) })
nuxt.hook('builder:generateApp', async () => { nuxt.hook('builder:generateApp', async () => {
await regenerateAutoImports() await regenerateImports()
}) })
} }
}) })
@ -147,7 +163,7 @@ function addDeclarationTemplates (ctx: Unimport) {
}) })
addTemplate({ addTemplate({
filename: 'types/auto-imports.d.ts', filename: 'types/imports.d.ts',
getContents: () => '// Generated by auto imports\n' + ctx.generateTypeDeclarations({ resolvePath: r }) getContents: () => '// Generated by auto imports\n' + ctx.generateTypeDeclarations({ resolvePath: r })
}) })
} }

View File

@ -2,12 +2,12 @@ import { pathToFileURL } from 'node:url'
import { createUnplugin } from 'unplugin' import { createUnplugin } from 'unplugin'
import { parseQuery, parseURL } from 'ufo' import { parseQuery, parseURL } from 'ufo'
import { Unimport } from 'unimport' import { Unimport } from 'unimport'
import { AutoImportsOptions } from '@nuxt/schema' import { ImportsOptions } from '@nuxt/schema'
import { normalize } from 'pathe' import { normalize } from 'pathe'
export const TransformPlugin = createUnplugin(({ ctx, options, sourcemap }: { ctx: Unimport, options: Partial<AutoImportsOptions>, sourcemap?: boolean }) => { export const TransformPlugin = createUnplugin(({ ctx, options, sourcemap }: { ctx: Unimport, options: Partial<ImportsOptions>, sourcemap?: boolean }) => {
return { return {
name: 'nuxt:auto-imports-transform', name: 'nuxt:imports-transform',
enforce: 'post', enforce: 'post',
transformInclude (id) { transformInclude (id) {
const { pathname, search } = parseURL(decodeURIComponent(pathToFileURL(id).href)) const { pathname, search } = parseURL(decodeURIComponent(pathToFileURL(id).href))
@ -39,7 +39,7 @@ export const TransformPlugin = createUnplugin(({ ctx, options, sourcemap }: { ct
async transform (code, id) { async transform (code, id) {
id = normalize(id) id = normalize(id)
const isNodeModule = id.match(/[\\/]node_modules[\\/]/) && !options.transform?.include?.some(pattern => id.match(pattern)) const isNodeModule = id.match(/[\\/]node_modules[\\/]/) && !options.transform?.include?.some(pattern => id.match(pattern))
// For modules in node_modules, we only transform `#imports` but not doing auto-imports // For modules in node_modules, we only transform `#imports` but not doing imports
if (isNodeModule && !code.match(/(['"])#imports\1/)) { if (isNodeModule && !code.match(/(['"])#imports\1/)) {
return return
} }

View File

@ -78,8 +78,8 @@ export default defineNuxtModule({
}) })
} }
nuxt.hook('autoImports:extend', (autoImports) => { nuxt.hook('imports:extend', (imports) => {
autoImports.push( imports.push(
{ name: 'definePageMeta', as: 'definePageMeta', from: resolve(runtimeDir, 'composables') }, { name: 'definePageMeta', as: 'definePageMeta', from: resolve(runtimeDir, 'composables') },
{ name: 'useLink', as: 'useLink', from: 'vue-router' } { name: 'useLink', as: 'useLink', from: 'vue-router' }
) )

View File

@ -4,10 +4,10 @@ import { join } from 'pathe'
import { createCommonJS, findExports } from 'mlly' import { createCommonJS, findExports } from 'mlly'
import * as VueFunctions from 'vue' import * as VueFunctions from 'vue'
import { createUnimport, Import } from 'unimport' import { createUnimport, Import } from 'unimport'
import { TransformPlugin } from '../src/auto-imports/transform' import { TransformPlugin } from '../src/imports/transform'
import { defaultPresets } from '../src/auto-imports/presets' import { defaultPresets } from '../src/imports/presets'
describe('auto-imports:transform', () => { describe('imports:transform', () => {
const imports: Import[] = [ const imports: Import[] = [
{ name: 'ref', as: 'ref', from: 'vue' }, { name: 'ref', as: 'ref', from: 'vue' },
{ name: 'computed', as: 'computed', from: 'bar' }, { name: 'computed', as: 'computed', from: 'bar' },
@ -54,7 +54,7 @@ describe('auto-imports:transform', () => {
const excludedNuxtHelpers = ['useHydration'] const excludedNuxtHelpers = ['useHydration']
describe('auto-imports:nuxt', () => { describe('imports:nuxt', () => {
try { try {
const { __dirname } = createCommonJS(import.meta.url) const { __dirname } = createCommonJS(import.meta.url)
const entrypointContents = readFileSync(join(__dirname, '../src/app/composables/index.ts'), 'utf8') const entrypointContents = readFileSync(join(__dirname, '../src/app/composables/index.ts'), 'utf8')
@ -170,7 +170,7 @@ const excludedVueHelpers = [
'compile' 'compile'
] ]
describe('auto-imports:vue', () => { describe('imports:vue', () => {
for (const name of Object.keys(VueFunctions)) { for (const name of Object.keys(VueFunctions)) {
if (excludedVueHelpers.includes(name)) { if (excludedVueHelpers.includes(name)) {
continue continue

View File

@ -24,14 +24,17 @@ export default {
} }
}, },
/** @deprecated Please use `imports` config. */
autoImports: null,
/** /**
* Configure how Nuxt auto-imports composables into your application. * Configure how Nuxt auto-imports composables into your application.
* *
* @see [Nuxt 3 documentation](https://v3.nuxtjs.org/guide/directory-structure/composables) * @see [Nuxt 3 documentation](https://v3.nuxtjs.org/guide/directory-structure/composables)
* @type {typeof import('../src/types/imports').AutoImportsOptions} * @type {typeof import('../src/types/imports').ImportsOptions}
* @version 3 * @version 3
*/ */
autoImports: { imports: {
global: false, global: false,
dirs: [] dirs: []
}, },

View File

@ -76,8 +76,15 @@ export interface NuxtHooks {
'build:manifest': (manifest: Manifest) => HookResult 'build:manifest': (manifest: Manifest) => HookResult
// Auto imports // Auto imports
'imports:sources': (presets: ImportPresetWithDeprecation[]) => HookResult
'imports:extend': (imports: Import[]) => HookResult
'imports:dirs': (dirs: string[]) => HookResult
/** @deprecated Please use `imports:sources` hook */
'autoImports:sources': (presets: ImportPresetWithDeprecation[]) => HookResult 'autoImports:sources': (presets: ImportPresetWithDeprecation[]) => HookResult
/** @deprecated Please use `imports:extend` hook */
'autoImports:extend': (imports: Import[]) => HookResult 'autoImports:extend': (imports: Import[]) => HookResult
/** @deprecated Please use `imports:dirs` hook */
'autoImports:dirs': (dirs: string[]) => HookResult 'autoImports:dirs': (dirs: string[]) => HookResult
// Components // Components

View File

@ -1,6 +1,6 @@
import { UnimportOptions } from 'unimport' import { UnimportOptions } from 'unimport'
export interface AutoImportsOptions extends UnimportOptions { export interface ImportsOptions extends UnimportOptions {
dirs?: string[] dirs?: string[]
global?: boolean global?: boolean
transform?: { transform?: {

View File

@ -7849,6 +7849,13 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"hookable@npm:^5.1.2":
version: 5.1.2
resolution: "hookable@npm:5.1.2"
checksum: 1b3fb622a26d34c9befe8991cf9ffcb575334ef66e151291bc4b3161e1a609365983d258020571bce4b52226d9b5880150d27ba9f4e4029734e5cd37ac31aa39
languageName: node
linkType: hard
"hosted-git-info@npm:^2.1.4": "hosted-git-info@npm:^2.1.4":
version: 2.8.9 version: 2.8.9
resolution: "hosted-git-info@npm:2.8.9" resolution: "hosted-git-info@npm:2.8.9"
@ -10266,7 +10273,7 @@ __metadata:
globby: ^13.1.2 globby: ^13.1.2
h3: ^0.7.15 h3: ^0.7.15
hash-sum: ^2.0.0 hash-sum: ^2.0.0
hookable: ^5.1.1 hookable: ^5.1.2
knitwork: ^0.1.2 knitwork: ^0.1.2
magic-string: ^0.26.2 magic-string: ^0.26.2
mlly: ^0.5.14 mlly: ^0.5.14