Skip to content

Commit e5bde90

Browse files
authored
refactor: cleanup build time logic (#3512)
1 parent 6d5fea9 commit e5bde90

3 files changed

Lines changed: 59 additions & 79 deletions

File tree

src/gen.ts

Lines changed: 21 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import { getLayerI18n, getLocaleFiles } from './utils'
77
import { asI18nVirtual } from './transform/utils'
88

99
import type { Nuxt } from '@nuxt/schema'
10-
import type { NuxtI18nOptions, LocaleInfo, LocaleObject, ExperimentalFeatures } from './types'
10+
import type { NuxtI18nOptions, LocaleObject, ExperimentalFeatures } from './types'
1111
import type { Locale } from 'vue-i18n'
1212
import type { I18nNuxtContext } from './context'
1313

@@ -39,7 +39,7 @@ export function simplifyLocaleOptions(
3939

4040
const locales = (options.locales ?? []) as LocaleObject[]
4141

42-
return locales.map(({ meta, ...locale }) => {
42+
return locales.map(locale => {
4343
if (!hasLocaleObjects) locale.code
4444
return formatLocaleFiles(nuxt, locale, options.experimental?.generatedLocaleFilePathFormat)
4545
})
@@ -60,32 +60,30 @@ export function generateLoaderOptions(
6060
) {
6161
debug('generateLoaderOptions: lazy', ctx.options.lazy)
6262

63-
const importMapper = new Map<string, LocaleLoaderData>()
64-
function generateLocaleImports(meta: NonNullable<LocaleInfo['meta']>[number]) {
65-
if (importMapper.has(meta.path)) return importMapper.get(meta.path)!
66-
const key = `locale_${genSafeVariableName(basename(meta.path))}_${meta.hash}`
67-
const specifier = asI18nVirtual(meta.hash)
68-
const async = genDynamicImport(specifier, { comment: `webpackChunkName: ${genString(key)}` })
69-
const sync = `() => Promise.resolve(${key})`
70-
71-
importMapper.set(meta.path, {
72-
specifier,
73-
key: genString(key),
74-
relative: meta.loadPath,
75-
cache: meta.file.cache ?? true,
76-
load: ctx.options.lazy ? async : sync,
77-
importString: genImport(specifier, key)
78-
})
79-
80-
return importMapper.get(meta.path)!
81-
}
82-
8363
/**
8464
* Prepare locale file imports
8565
*/
66+
const importMapper = new Map<string, LocaleLoaderData>()
8667
const localeLoaders: Record<string, LocaleLoaderData[]> = {}
8768
for (const locale of ctx.localeInfo) {
88-
localeLoaders[locale.code] = (locale?.meta ?? []).map(meta => generateLocaleImports(meta))
69+
localeLoaders[locale.code] ??= []
70+
for (const meta of locale.meta) {
71+
if (!importMapper.has(meta.path)) {
72+
const key = `locale_${genSafeVariableName(basename(meta.path))}_${meta.hash}`
73+
const specifier = asI18nVirtual(meta.hash)
74+
importMapper.set(meta.path, {
75+
specifier,
76+
key: genString(key),
77+
relative: meta.loadPath,
78+
cache: meta.file.cache ?? true,
79+
load: ctx.options.lazy
80+
? genDynamicImport(specifier, { comment: `webpackChunkName: ${genString(key)}` })
81+
: `() => Promise.resolve(${key})`,
82+
importString: genImport(specifier, key)
83+
})
84+
}
85+
localeLoaders[locale.code].push(importMapper.get(meta.path)!)
86+
}
8987
}
9088

9189
/**
@@ -94,7 +92,6 @@ export function generateLoaderOptions(
9492
const vueI18nConfigs = []
9593
for (let i = ctx.vueI18nConfigPaths.length - 1; i >= 0; i--) {
9694
const config = ctx.vueI18nConfigPaths[i]
97-
if (config.meta.path === '') continue
9895
const key = genString(`config_${genSafeVariableName(basename(config.meta.path))}_${config.meta.hash}`)
9996
const specifier = asI18nVirtual(config.meta.hash)
10097
const importer = genDynamicImport(specifier, { comment: `webpackChunkName: ${key}` })

src/layers.ts

Lines changed: 31 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import type { LocaleObject, NuxtI18nOptions, VueI18nConfigPathInfo } from './typ
1212

1313
const debug = createDebug('@nuxtjs/i18n:layers')
1414

15-
export const checkLayerOptions = (_options: NuxtI18nOptions, nuxt: Nuxt) => {
15+
export function checkLayerOptions(_options: NuxtI18nOptions, nuxt: Nuxt) {
1616
const logger = useLogger(NUXT_I18N_MODULE_ID)
1717
const project = nuxt.options._layers[0]
1818
const layers = nuxt.options._layers
@@ -21,32 +21,28 @@ export const checkLayerOptions = (_options: NuxtI18nOptions, nuxt: Nuxt) => {
2121
const layerI18n = getLayerI18n(layer)
2222
if (layerI18n == null) continue
2323

24-
const configLocation = project.config.rootDir === layer.config.rootDir ? 'project layer' : 'extended layer'
25-
const layerHint = `In ${configLocation} (\`${resolve(project.config.rootDir, layer.configFile)}\`) -`
24+
const configLocation = project.config.rootDir === layer.config.rootDir ? 'project' : 'extended'
25+
const layerHint = `In ${configLocation} layer (\`${resolve(project.config.rootDir, layer.configFile)}\`) -`
2626

2727
try {
2828
// check `langDir` option
2929
if (layerI18n.langDir) {
30-
const locales = layerI18n.locales || []
31-
3230
if (isString(layerI18n.langDir) && isAbsolute(layerI18n.langDir)) {
3331
logger.warn(
3432
`${layerHint} \`langDir\` is set to an absolute path (\`${layerI18n.langDir}\`) but should be set a path relative to \`srcDir\` (\`${layer.config.srcDir}\`). ` +
3533
`Absolute paths will not work in production, see https://i18n.nuxtjs.org/options/lazy#langdir for more details.`
3634
)
3735
}
3836

39-
for (const locale of locales) {
37+
for (const locale of layerI18n.locales ?? []) {
4038
if (isString(locale)) {
4139
throw new Error('When using the `langDir` option the `locales` must be a list of objects.')
4240
}
43-
44-
if (!(locale.file || locale.files)) {
45-
throw new Error(
46-
'All locales must have the `file` or `files` property set when using `langDir`.\n' +
47-
`Found none in:\n${JSON.stringify(locale, null, 2)}.`
48-
)
49-
}
41+
if (locale.file || locale.files) continue
42+
throw new Error(
43+
'All locales must have the `file` or `files` property set when using `langDir`.\n' +
44+
`Found none in:\n${JSON.stringify(locale, null, 2)}.`
45+
)
5046
}
5147
}
5248
} catch (err) {
@@ -56,19 +52,7 @@ export const checkLayerOptions = (_options: NuxtI18nOptions, nuxt: Nuxt) => {
5652
}
5753
}
5854

59-
/**
60-
* Merges `locales` configured by each layer and resolves the locale `files` to absolute paths.
61-
*
62-
* This overwrites `options.locales`
63-
*/
64-
export const applyLayerOptions = (options: NuxtI18nOptions, nuxt: Nuxt) => {
65-
const mergedLocales = mergeLayerLocales(options, nuxt)
66-
debug('merged locales', mergedLocales)
67-
68-
options.locales = mergedLocales
69-
}
70-
71-
export const mergeLayerPages = (analyzer: (pathOverride: string) => void, nuxt: Nuxt) => {
55+
export function mergeLayerPages(analyzer: (pathOverride: string) => void, nuxt: Nuxt) {
7256
const project = nuxt.options._layers[0]
7357
const layers = nuxt.options._layers
7458

@@ -86,7 +70,6 @@ export function resolveI18nDir(layer: NuxtConfigLayer, i18n: NuxtI18nOptions, fr
8670
if (i18n.restructureDir !== false) {
8771
return resolve(layer.config.rootDir, i18n.restructureDir ?? 'i18n')
8872
}
89-
9073
return resolve(layer.config.rootDir, fromRootDir ? '' : layer.config.srcDir)
9174
}
9275

@@ -96,25 +79,25 @@ function resolveLayerLangDir(layer: NuxtConfigLayer, i18n: NuxtI18nOptions) {
9679
return resolve(resolveI18nDir(layer, i18n), i18n.langDir)
9780
}
9881

99-
const mergeLayerLocales = (options: NuxtI18nOptions, nuxt: Nuxt) => {
100-
debug('project layer `lazy` option', options.lazy)
82+
/**
83+
* Merges `locales` configured by each layer and resolves the locale `files` to absolute paths.
84+
* This overwrites `options.locales`
85+
*/
86+
export function applyLayerOptions(options: NuxtI18nOptions, nuxt: Nuxt) {
10187
options.locales ??= []
10288

10389
const configs: LocaleConfig[] = []
104-
10590
for (const layer of nuxt.options._layers) {
10691
const i18n = getLayerI18n(layer)
10792
if (i18n?.locales == null) continue
108-
109-
configs.push(assign({}, i18n, { langDir: resolveLayerLangDir(layer, i18n) }))
93+
configs.push(assign({}, i18n, { langDir: resolveLayerLangDir(layer, i18n), locales: i18n.locales }))
11094
}
11195

112-
const installModuleConfigMap = new Map<string, LocaleConfig>()
113-
11496
/**
11597
* Collect any locale files that are not provided by layers these are added when
11698
* installing through `installModule` and should have absolute paths.
11799
*/
100+
const installModuleConfigMap = new Map<string, LocaleConfig>()
118101
outer: for (const locale of options.locales) {
119102
if (isString(locale)) continue
120103

@@ -136,27 +119,28 @@ const mergeLayerLocales = (options: NuxtI18nOptions, nuxt: Nuxt) => {
136119

137120
configs.unshift(...installModuleConfigMap.values())
138121

139-
return mergeConfigLocales(configs)
122+
debug('merged locales', configs)
123+
options.locales = mergeConfigLocales(configs)
140124
}
141125

142126
export async function resolveLayerVueI18nConfigInfo(options: NuxtI18nOptions) {
143127
const logger = useLogger(NUXT_I18N_MODULE_ID)
144128
const nuxt = useNuxt()
145129

146-
const resolveArr = nuxt.options._layers.map(async layer => {
147-
const i18n = getLayerI18n(layer)
148-
const i18nDirPath = resolveI18nDir(layer, i18n || {}, true)
149-
const res = await resolveVueI18nConfigInfo(i18nDirPath, i18n?.vueI18n)
150-
151-
if (res == null && i18n?.vueI18n != null) {
152-
logger.warn(`Vue I18n configuration file \`${i18n.vueI18n}\` not found in \`${i18nDirPath}\`. Skipping...`)
153-
return undefined
154-
}
130+
const resolved = await Promise.all(
131+
nuxt.options._layers.map(async layer => {
132+
const i18n = getLayerI18n(layer)
133+
const i18nDirPath = resolveI18nDir(layer, i18n || {}, true)
134+
const res = await resolveVueI18nConfigInfo(i18nDirPath, i18n?.vueI18n)
155135

156-
return res
157-
})
136+
if (res == null && i18n?.vueI18n != null) {
137+
logger.warn(`Vue I18n configuration file \`${i18n.vueI18n}\` not found in \`${i18nDirPath}\`. Skipping...`)
138+
return undefined
139+
}
158140

159-
const resolved = await Promise.all(resolveArr)
141+
return res
142+
})
143+
)
160144

161145
// use `vueI18n` passed by `installModule`
162146
if (options.vueI18n && isAbsolute(options.vueI18n)) {

src/utils.ts

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -170,8 +170,8 @@ export function resolveRelativeLocales(locale: LocaleObject, config: LocaleConfi
170170
}
171171

172172
export type LocaleConfig = {
173-
langDir?: string | null
174-
locales?: string[] | LocaleObject[]
173+
langDir: string
174+
locales: string[] | LocaleObject[]
175175
}
176176

177177
/**
@@ -215,27 +215,26 @@ export const mergeConfigLocales = (configs: LocaleConfig[], baseLocales: LocaleO
215215
return Array.from(mergedLocales.values())
216216
}
217217

218-
type RegisterModuleArg = Pick<NuxtI18nOptions, 'langDir' | 'locales'>
219-
220218
/**
221219
* Merges project layer locales with registered i18n modules
222220
*/
223221
export const mergeI18nModules = async (options: NuxtI18nOptions, nuxt: Nuxt) => {
224-
options.i18nModules = []
222+
const i18nModules: LocaleConfig[] = []
225223

226224
await nuxt.callHook(
227225
'i18n:registerModule',
228-
(config: RegisterModuleArg) => config.langDir && options.i18nModules!.push(config)
226+
config => config.langDir && config.locales && i18nModules.push({ langDir: config.langDir, locales: config.locales })
229227
)
230228

231-
if (options.i18nModules.length > 0) {
229+
if (i18nModules.length > 0) {
232230
const baseLocales: LocaleObject[] = []
233231
for (const locale of options.locales!) {
234232
if (!isObject(locale)) continue
235233
baseLocales.push(assign({}, locale, { file: undefined, files: getLocaleFiles(locale) }))
236234
}
237-
options.locales = mergeConfigLocales(options.i18nModules, baseLocales)
235+
options.locales = mergeConfigLocales(i18nModules, baseLocales)
238236
}
237+
options.i18nModules = i18nModules
239238
}
240239

241240
function getHash(text: BinaryLike): string {

0 commit comments

Comments
 (0)