Skip to content

Commit

Permalink
fix: resolve i18n.config paths in nuxt layers with unplugin simplefic…
Browse files Browse the repository at this point in the history
  • Loading branch information
kazupon committed Jul 27, 2023
1 parent 7711f44 commit ea642d7
Show file tree
Hide file tree
Showing 7 changed files with 36 additions and 180 deletions.
22 changes: 11 additions & 11 deletions playground/nuxt.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ export default defineNuxtConfig({
// }
// }
// },
debug: false,
debug: true,
i18n: {
experimental: {
jsTsFormatResource: true
Expand Down Expand Up @@ -148,12 +148,12 @@ export default defineNuxtConfig({
}
],
// trailingSlash: true,
debug: false,
debug: true,
defaultLocale: 'en',
// strategy: 'no_prefix',
// strategy: 'prefix',
// strategy: 'prefix_and_default',
strategy: 'prefix_except_default',
// strategy: 'prefix_except_default',
// rootRedirect: '/ja/about-ja',
dynamicRouteParams: true,
// customRoutes: 'config',
Expand All @@ -167,14 +167,14 @@ export default defineNuxtConfig({
},
// differentDomains: true,
// skipSettingLocaleOnNavigate: true,
// detectBrowserLanguage: false,
detectBrowserLanguage: {
useCookie: true
// alwaysRedirect: true
// cookieKey: 'i18n_redirected',
// // cookieKey: 'my_custom_cookie_name',
// redirectOn: 'root'
},
detectBrowserLanguage: false,
// detectBrowserLanguage: {
// // useCookie: true
// // alwaysRedirect: true
// // cookieKey: 'i18n_redirected',
// // // cookieKey: 'my_custom_cookie_name',
// // redirectOn: 'root'
// },
vueI18n: './vue-i18n.options.ts'
}
})
15 changes: 4 additions & 11 deletions src/bundler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@ import { extendWebpackConfig, extendViteConfig, addWebpackPlugin, addVitePlugin
import VueI18nWebpackPlugin from '@intlify/unplugin-vue-i18n/webpack'
import VueI18nVitePlugin from '@intlify/unplugin-vue-i18n/vite'
import { TransformMacroPlugin, TransformMacroPluginOptions } from './transform/macros'
import { ResourceProxyPlugin, ResourceProxyPluginOptions } from './transform/proxy'
import { ResourceDynamicPlugin, ResourceDynamicPluginOptions } from './transform/dynamic'
import { ResourcePlugin, ResourcePluginOptions } from './transform/resource'
import { assign } from '@intlify/shared'
import { getLayerLangPaths } from './layers'

Expand Down Expand Up @@ -33,16 +32,12 @@ export async function extendBundler(
debug('i18nModulePaths -', i18nModulePaths)
const localePaths = [...langPaths, ...i18nModulePaths]

const proxyOptions: ResourceProxyPluginOptions = {
sourcemap: nuxt.options.sourcemap.server || nuxt.options.sourcemap.client
}

// extract macros from components
const macroOptions: TransformMacroPluginOptions = {
sourcemap: nuxt.options.sourcemap.server || nuxt.options.sourcemap.client
}

const dynamicOptions: ResourceDynamicPluginOptions = {
const resourceOptions: ResourcePluginOptions = {
sourcemap: nuxt.options.sourcemap.server || nuxt.options.sourcemap.client
}

Expand All @@ -66,10 +61,9 @@ export async function extendBundler(
webpackPluginOptions.include = localePaths.map(x => resolve(x, './**'))
}

addWebpackPlugin(ResourceProxyPlugin.webpack(proxyOptions))
addWebpackPlugin(VueI18nWebpackPlugin(webpackPluginOptions))
addWebpackPlugin(TransformMacroPlugin.webpack(macroOptions))
addWebpackPlugin(ResourceDynamicPlugin.webpack(dynamicOptions))
addWebpackPlugin(ResourcePlugin.webpack(resourceOptions))

extendWebpackConfig(config => {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- `config.plugins` is safe, so it's assigned with nuxt!
Expand Down Expand Up @@ -98,10 +92,9 @@ export async function extendBundler(
vitePluginOptions.include = localePaths.map(x => resolve(x, './**'))
}

addVitePlugin(ResourceProxyPlugin.vite(proxyOptions))
addVitePlugin(VueI18nVitePlugin(vitePluginOptions))
addVitePlugin(TransformMacroPlugin.vite(macroOptions))
addVitePlugin(ResourceDynamicPlugin.vite(dynamicOptions))
addVitePlugin(ResourcePlugin.vite(resourceOptions))

extendViteConfig(config => {
if (config.define) {
Expand Down
2 changes: 0 additions & 2 deletions src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,6 @@ export const DEFAULT_OPTIONS = {
debug: false
} as const

export const NUXT_I18N_LOCALE_PROXY_ID = '@nuxtjs/i18n/__locale__' as const
export const NUXT_I18N_CONFIG_PROXY_ID = '@nuxtjs/i18n/__config__' as const
export const NUXT_I18N_TEMPLATE_OPTIONS_KEY = 'i18n.options.mjs' as const
export const NUXT_I18N_COMPOSABLE_DEFINE_ROUTE = 'defineI18nRoute' as const
export const NUXT_I18N_COMPOSABLE_DEFINE_LOCALE = 'defineI18nLocale' as const
Expand Down
31 changes: 12 additions & 19 deletions src/gen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,10 @@
import createDebug from 'debug'
import { isArray, isObject } from '@intlify/shared'
import { generateJSON } from '@intlify/bundle-utils'
import {
EXECUTABLE_EXTENSIONS,
NULL_HASH,
NUXT_I18N_MODULE_ID,
NUXT_I18N_CONFIG_PROXY_ID,
NUXT_I18N_LOCALE_PROXY_ID
} from './constants'
import { EXECUTABLE_EXTENSIONS, NULL_HASH, NUXT_I18N_MODULE_ID } from './constants'
import { genImport, genSafeVariableName, genDynamicImport } from 'knitwork'
import { parse as parsePath, normalize } from 'pathe'
import { withQuery } from 'ufo'
import { asVirtualId } from './transform/utils'
import { toCode } from './utils'

import type { NuxtI18nOptions, NuxtI18nInternalOptions, LocaleInfo, VueI18nConfigPathInfo, LocaleType } from './types'
Expand All @@ -29,6 +22,8 @@ export type LoaderOptions = {
additionalMessages?: AdditionalMessages // TODO: remove `i18n:extend-messages` before v8 official release
}

type ResourceType = 'locale' | 'config'

const debug = createDebug('@nuxtjs/i18n:gen')

export function generateLoaderOptions(
Expand Down Expand Up @@ -85,7 +80,7 @@ export function generateLoaderOptions(
gen += `${genImport(
genImportSpecifier(loadPath, ext, absolutePath, type, {
hash,
virtualId: NUXT_I18N_LOCALE_PROXY_ID,
resourceType: 'locale',
query: { locale: localeCode }
}),
variableName,
Expand Down Expand Up @@ -179,7 +174,7 @@ export function generateLoaderOptions(
`
const basicVueI18nConfigCode = generateVueI18nConfigration(vueI18nConfigPathInfo, ({ absolute: absolutePath, relative: relativePath, hash, relativeBase, type }, { dir, base, ext }) => {
const configImportKey = makeImportKey(relativeBase, dir, base)
return `const vueI18n = await vueI18nConfigLoader((${genDynamicImport(genImportSpecifier(configImportKey, ext, absolutePath, type, { hash, virtualId: NUXT_I18N_CONFIG_PROXY_ID }), { comment: `webpackChunkName: "${normalizeWithUnderScore(relativePath)}_${hash}"` })}))\n`
return `const vueI18n = await vueI18nConfigLoader((${genDynamicImport(genImportSpecifier(configImportKey, ext, absolutePath, type, { hash, resourceType: 'config' }), { comment: `webpackChunkName: "${normalizeWithUnderScore(relativePath)}_${hash}"` })}))\n`
})
if (basicVueI18nConfigCode != null) {
genCodes += ` ${basicVueI18nConfigCode}`
Expand Down Expand Up @@ -218,7 +213,7 @@ export function generateLoaderOptions(
for (const configPath of vueI18nConfigPaths) {
const additionalVueI18nConfigCode = generateVueI18nConfigration(configPath, ({ absolute: absolutePath, relative: relativePath, hash, relativeBase, type }, { dir, base, ext }) => {
const configImportKey = makeImportKey(relativeBase, dir, base)
return `await mergeMessages(${rootKey}.${key}.messages, (${genDynamicImport(genImportSpecifier(configImportKey, ext, absolutePath, type, { hash, virtualId: NUXT_I18N_CONFIG_PROXY_ID }), { comment: `webpackChunkName: "${normalizeWithUnderScore(relativePath)}_${hash}"` })}))\n`
return `await mergeMessages(${rootKey}.${key}.messages, (${genDynamicImport(genImportSpecifier(configImportKey, ext, absolutePath, type, { hash, resourceType: 'config' }), { comment: `webpackChunkName: "${normalizeWithUnderScore(relativePath)}_${hash}"` })}))\n`
})
if (additionalVueI18nConfigCode != null) {
genCodes += ` ${additionalVueI18nConfigCode}`
Expand Down Expand Up @@ -280,8 +275,6 @@ export function generateLoaderOptions(
return genCode
}

type TransformProxyType = typeof NUXT_I18N_LOCALE_PROXY_ID | typeof NUXT_I18N_CONFIG_PROXY_ID

function raiseSyntaxError(path: string) {
throw new Error(`'unknown' type in '${path}'.`)
}
Expand All @@ -293,21 +286,21 @@ function genImportSpecifier(
type: LocaleType,
{
hash = NULL_HASH,
virtualId = NUXT_I18N_LOCALE_PROXY_ID,
resourceType = 'locale',
query = {}
}: {
hash?: string
virtualId?: TransformProxyType
resourceType?: ResourceType
query?: Record<string, string>
} = {}
) {
if (EXECUTABLE_EXTENSIONS.includes(ext)) {
if (virtualId === NUXT_I18N_LOCALE_PROXY_ID) {
if (resourceType === 'locale') {
type === 'unknown' && raiseSyntaxError(absolutePath)
return type === 'dynamic' ? asVirtualId(withQuery(virtualId, { target: id, hash, ...query })) : id
} else if (virtualId === NUXT_I18N_CONFIG_PROXY_ID) {
return type === 'dynamic' ? withQuery(id, { hash, ...query }) : id
} else if (resourceType === 'config') {
type === 'unknown' && raiseSyntaxError(absolutePath)
return asVirtualId(withQuery(virtualId, { target: id, hash, ...query }))
return withQuery(id, { hash, ...query, ...{ config: 1 } })
} else {
return id
}
Expand Down
6 changes: 5 additions & 1 deletion src/runtime/internal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ async function loadMessage(context: NuxtApp, loader: () => Promise<any>, locale:
const getter = await loader().then(r => r.default || r)
if (isFunction(getter)) {
if (i18nConfig.experimental?.jsTsFormatResource) {
message = await getter(locale).then((r: any) => r.default || r)
message = await getter(locale)
__DEBUG__ && console.log('loadMessage: dynamic load', message)
} else {
console.warn(
Expand Down Expand Up @@ -167,8 +167,10 @@ export async function loadLocale(
const { key, load } = loaders[0]
let message: LocaleMessages<DefineLocaleMessage> | undefined | null = null
if (loadedMessages.has(key)) {
__DEBUG__ && console.log(key + ' is already loaded')
message = loadedMessages.get(key)
} else {
__DEBUG__ && console.log(key + ' is loading ...')
message = await loadMessage(context, load, locale)
if (message != null) {
loadedMessages.set(key, message)
Expand All @@ -183,8 +185,10 @@ export async function loadLocale(
for (const { key, load } of loaders) {
let message: LocaleMessages<DefineLocaleMessage> | undefined | null = null
if (loadedMessages.has(key)) {
__DEBUG__ && console.log(key + ' is already loaded')
message = loadedMessages.get(key)
} else {
__DEBUG__ && console.log(key + ' is loading ...')
message = await loadMessage(context, load, locale)
if (message != null) {
loadedMessages.set(key, message)
Expand Down
132 changes: 0 additions & 132 deletions src/transform/proxy.ts

This file was deleted.

8 changes: 4 additions & 4 deletions src/transform/dynamic.ts → src/transform/resource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,17 @@ import MagicString from 'magic-string'
import { VIRTUAL_PREFIX_HEX } from './utils'
import { NUXT_I18N_COMPOSABLE_DEFINE_LOCALE, NUXT_I18N_COMPOSABLE_DEFINE_CONFIG } from '../constants'

export interface ResourceDynamicPluginOptions {
export interface ResourcePluginOptions {
sourcemap?: boolean
}

const debug = createDebug('@nuxtjs/i18n:transform:dynamic')
const debug = createDebug('@nuxtjs/i18n:transform:resource')

export const ResourceDynamicPlugin = createUnplugin((options: ResourceDynamicPluginOptions) => {
export const ResourcePlugin = createUnplugin((options: ResourcePluginOptions) => {
debug('options', options)

return {
name: 'nuxtjs:i18n-resource-dynamic',
name: 'nuxtjs:i18n-resource',
enforce: 'post',

transformInclude(id) {
Expand Down

0 comments on commit ea642d7

Please sign in to comment.