Skip to content

Commit

Permalink
fix: cannot resolve langDir path for locales file path (nuxt-modules#…
Browse files Browse the repository at this point in the history
…1846)

* fix: cannot resolve langDir path for locales file path

* fix: ci

* add avoid vitest issue
  • Loading branch information
kazupon authored Feb 10, 2023
1 parent 1e6d03d commit 6842421
Show file tree
Hide file tree
Showing 4 changed files with 111 additions and 32 deletions.
56 changes: 32 additions & 24 deletions src/gen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,30 +47,34 @@ export function generateLoaderOptions(
const generatedImports = new Map<string, string>()
const importMapper = new Map<string, string>()

function generateSyncImports(gen: string, path?: string) {
if (!path) {
const buildImportKey = (root: string, dir: string, base: string) =>
normalize(`${root ? `${root}/` : ''}${dir ? `${dir}/` : ''}${base}`)

function generateSyncImports(gen: string, filepath?: string) {
if (!filepath) {
return gen
}

const { base, ext } = parsePath(path)
if (!generatedImports.has(base)) {
let loadPath = path
const { root, dir, base, ext } = parsePath(filepath)
const key = buildImportKey(root, dir, base)
if (!generatedImports.has(key)) {
let loadPath = filepath
if (langDir) {
loadPath = resolveLocaleRelativePath(localesRelativeBase, langDir, base)
loadPath = resolveLocaleRelativePath(localesRelativeBase, langDir, filepath)
}
const assertFormat = ext.slice(1)
const variableName = genSafeVariableName(`locale_${convertToImportId(base)}`)
const variableName = genSafeVariableName(`locale_${convertToImportId(key)}`)
gen += `${genImport(loadPath, variableName, assertFormat ? { assert: { type: assertFormat } } : {})}\n`
importMapper.set(base, variableName)
generatedImports.set(base, loadPath)
importMapper.set(key, variableName)
generatedImports.set(key, loadPath)
}

return gen
}

for (const { path, paths } of syncLocaleFiles) {
;(path ? [path] : paths || []).forEach(p => {
genCode = generateSyncImports(genCode, p)
for (const { file, files } of syncLocaleFiles) {
;(file ? [file] : files || []).forEach(f => {
genCode = generateSyncImports(genCode, f)
})
}

Expand Down Expand Up @@ -113,19 +117,21 @@ export function generateLoaderOptions(
} else if (rootKey === 'localeInfo') {
let codes = `export const localeMessages = {\n`
if (langDir) {
for (const { code, path, paths } of syncLocaleFiles) {
const syncPaths = path ? [path] : paths || []
codes += ` ${toCode(code)}: [${syncPaths.map(path => {
const { base } = parsePath(path)
return `{ key: ${toCode(generatedImports.get(base))}, load: () => Promise.resolve(${importMapper.get(base)}) }`
for (const { code, file, files} of syncLocaleFiles) {
const syncPaths = file ? [file] : files|| []
codes += ` ${toCode(code)}: [${syncPaths.map(filepath => {
const { root, dir, base } = parsePath(filepath)
const key = buildImportKey(root, dir, base)
return `{ key: ${toCode(generatedImports.get(key))}, load: () => Promise.resolve(${importMapper.get(key)}) }`
})}],\n`
}
for (const { code, path, paths } of asyncLocaleFiles) {
const dynamicPaths = path ? [path] : paths || []
codes += ` ${toCode(code)}: [${dynamicPaths.map(path => {
const { base } = parsePath(path)
const loadPath = resolveLocaleRelativePath(localesRelativeBase, langDir, base)
return `{ key: ${toCode(loadPath)}, load: ${genDynamicImport(loadPath, { comment: `webpackChunkName: "lang-${base}"` })} }`
for (const { code, file, files } of asyncLocaleFiles) {
const dynamicPaths = file ? [file] : files || []
codes += ` ${toCode(code)}: [${dynamicPaths.map(filepath => {
const { root, dir, base } = parsePath(filepath)
const key = buildImportKey(root, dir, base)
const loadPath = resolveLocaleRelativePath(localesRelativeBase, langDir, filepath)
return `{ key: ${toCode(loadPath)}, load: ${genDynamicImport(loadPath, { comment: `webpackChunkName: "lang_${normalizeWithUnderScore(key)}"` })} }`
})}],\n`
}
}
Expand All @@ -148,13 +154,15 @@ export function generateLoaderOptions(

const IMPORT_ID_CACHES = new Map<string, string>()

const normalizeWithUnderScore = (name: string) => name.replace(/-/g, '_').replace(/\./g, '_').replace(/\//g, '_')

function convertToImportId(file: string) {
if (IMPORT_ID_CACHES.has(file)) {
return IMPORT_ID_CACHES.get(file)
}

const { name } = parsePath(file)
const id = name.replace(/-/g, '_').replace(/\./g, '_')
const id = normalizeWithUnderScore(name)
IMPORT_ID_CACHES.set(file, id)

return id
Expand Down
44 changes: 36 additions & 8 deletions test/__snapshots__/gen.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,37 @@ exports[`lazy 1`] = `
"export const localeCodes = [\\"en\\",\\"ja\\",\\"fr\\"]
export const localeMessages = {
\\"en\\": [{ key: \\"../locales/en.json\\", load: () => import(\\"../locales/en.json\\" /* webpackChunkName: \\"lang-en.json\\" */) }],
\\"ja\\": [{ key: \\"../locales/ja.json\\", load: () => import(\\"../locales/ja.json\\" /* webpackChunkName: \\"lang-ja.json\\" */) }],
\\"fr\\": [{ key: \\"../locales/fr.json\\", load: () => import(\\"../locales/fr.json\\" /* webpackChunkName: \\"lang-fr.json\\" */) }],
\\"en\\": [{ key: \\"../locales/en.json\\", load: () => import(\\"../locales/en.json\\" /* webpackChunkName: \\"lang_en_json_en_json\\" */) }],
\\"ja\\": [{ key: \\"../locales/ja.json\\", load: () => import(\\"../locales/ja.json\\" /* webpackChunkName: \\"lang_ja_json_ja_json\\" */) }],
\\"fr\\": [{ key: \\"../locales/fr.json\\", load: () => import(\\"../locales/fr.json\\" /* webpackChunkName: \\"lang_fr_json_fr_json\\" */) }],
}
export const additionalMessages = Object({})
export const resolveNuxtI18nOptions = async (context) => {
const nuxtI18nOptions = Object({})
nuxtI18nOptions.defaultLocale = \\"en\\"
const vueI18nOptionsLoader = async (context) => Object({\\"locale\\":\\"en\\",\\"fallbackLocale\\":\\"fr\\",\\"messages\\": Object({\\"en\\":{
\\"hello\\": (()=>{const fn=(ctx) => {const { normalize: _normalize } = ctx;return _normalize([\\"Hello!\\"])};fn.source=\\"Hello!\\";return fn;})()
},}),})
nuxtI18nOptions.vueI18n = await vueI18nOptionsLoader(context)
return nuxtI18nOptions
}
export const nuxtI18nInternalOptions = Object({__normalizedLocales: [Object({\\"code\\":\\"en\\"})]})
export const NUXT_I18N_MODULE_ID = \\"@nuxtjs/i18n\\"
export const isSSG = false
export const isSSR = true
"
`;

exports[`locale file in nested 1`] = `
"export const localeCodes = [\\"en\\",\\"ja\\",\\"fr\\"]
export const localeMessages = {
\\"en\\": [{ key: \\"../locales/en/main.json\\", load: () => import(\\"../locales/en/main.json\\" /* webpackChunkName: \\"lang_en_en_main_json\\" */) }],
\\"ja\\": [{ key: \\"../locales/ja/main.json\\", load: () => import(\\"../locales/ja/main.json\\" /* webpackChunkName: \\"lang_ja_ja_main_json\\" */) }],
\\"fr\\": [{ key: \\"../locales/fr/main.json\\", load: () => import(\\"../locales/fr/main.json\\" /* webpackChunkName: \\"lang_fr_fr_main_json\\" */) }],
}
export const additionalMessages = Object({})
Expand All @@ -65,11 +93,11 @@ exports[`multiple files 1`] = `
"export const localeCodes = [\\"en\\",\\"ja\\",\\"fr\\",\\"es\\",\\"es-AR\\"]
export const localeMessages = {
\\"en\\": [{ key: \\"../locales/en.json\\", load: () => import(\\"../locales/en.json\\" /* webpackChunkName: \\"lang-en.json\\" */) }],
\\"ja\\": [{ key: \\"../locales/ja.json\\", load: () => import(\\"../locales/ja.json\\" /* webpackChunkName: \\"lang-ja.json\\" */) }],
\\"fr\\": [{ key: \\"../locales/fr.json\\", load: () => import(\\"../locales/fr.json\\" /* webpackChunkName: \\"lang-fr.json\\" */) }],
\\"es\\": [{ key: \\"../locales/es.json\\", load: () => import(\\"../locales/es.json\\" /* webpackChunkName: \\"lang-es.json\\" */) }],
\\"es-AR\\": [{ key: \\"../locales/es.json\\", load: () => import(\\"../locales/es.json\\" /* webpackChunkName: \\"lang-es.json\\" */) },{ key: \\"../locales/es-AR.json\\", load: () => import(\\"../locales/es-AR.json\\" /* webpackChunkName: \\"lang-es-AR.json\\" */) }],
\\"en\\": [{ key: \\"../locales/en.json\\", load: () => import(\\"../locales/en.json\\" /* webpackChunkName: \\"lang_en_json_en_json\\" */) }],
\\"ja\\": [{ key: \\"../locales/ja.json\\", load: () => import(\\"../locales/ja.json\\" /* webpackChunkName: \\"lang_ja_json_ja_json\\" */) }],
\\"fr\\": [{ key: \\"../locales/fr.json\\", load: () => import(\\"../locales/fr.json\\" /* webpackChunkName: \\"lang_fr_json_fr_json\\" */) }],
\\"es\\": [{ key: \\"../locales/es.json\\", load: () => import(\\"../locales/es.json\\" /* webpackChunkName: \\"lang_es_json_es_json\\" */) }],
\\"es-AR\\": [{ key: \\"../locales/es.json\\", load: () => import(\\"../locales/es.json\\" /* webpackChunkName: \\"lang_es_json_es_json\\" */) },{ key: \\"../locales/es-AR.json\\", load: () => import(\\"../locales/es-AR.json\\" /* webpackChunkName: \\"lang_es_AR_json_es_AR_json\\" */) }],
}
export const additionalMessages = Object({})
Expand Down
34 changes: 34 additions & 0 deletions test/gen.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,40 @@ test('multiple files', () => {
expect(code).toMatchSnapshot()
})

test('locale file in nested', () => {
const code = generateLoaderOptions(
true,
'locales',
'..',
{
localeCodes: LOCALE_CODES,
localeInfo: [
{
code: 'en',
file: 'en/main.json',
path: '/path/to/en.json'
},
{
code: 'ja',
file: 'ja/main.json',
path: '/path/to/ja.json'
},
{
code: 'fr',
file: 'fr/main.json',
path: '/path/to/fr.json'
}
],
additionalMessages: {},
nuxtI18nOptions: NUXT_I18N_OPTIONS,
nuxtI18nInternalOptions: NUXT_I18N_INTERNAL_OPTIONS
},
{ ssg: false, ssr: true, dev: true }
)
expect(validateSyntax(code)).toBe(true)
expect(code).toMatchSnapshot()
})

test('vueI18n: path', () => {
const code = generateLoaderOptions(
false,
Expand Down
9 changes: 9 additions & 0 deletions test/pages/custom_route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,15 @@ import { NuxtPageAnalizeContext, AnalizedNuxtPageMeta } from '../../src/pages'
import type { NuxtI18nOptions } from '../../src/types'
import type { NuxtPage } from './utils'

/**
* NOTE:
* This teardown is to avoid the weird issue of vitest.
* https://github.com/vitest-dev/vitest/issues/2845#issuecomment-1424666525
*/
afterAll(() => {
vi.restoreAllMocks()
})

describe.each([
{
case: 'simple',
Expand Down

0 comments on commit 6842421

Please sign in to comment.