Skip to content

Commit

Permalink
refactor: add Vite compatibility when lazy loading (nuxt-modules#1084)
Browse files Browse the repository at this point in the history
Co-authored-by: Rafał Chłodnicki <rchl2k@gmail.com>
Co-authored-by: Pooya Parsa <pyapar@gmail.com>
  • Loading branch information
3 people authored Mar 4, 2021
1 parent 7b8f77d commit 9b357da
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 8 deletions.
5 changes: 5 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,11 @@ export default function (userOptions) {
return
}

// Resolve langDir
if (options.langDir) {
options.langDir = this.nuxt.resolver.resolveAlias(options.langDir)
}

// Templates (including plugins).
// This is done here rather than in the build hook to ensure the order the plugins are added
// is predictable between different modules.
Expand Down
8 changes: 8 additions & 0 deletions src/templates/options.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,11 @@ for (const [key, value] of Object.entries(options)) {
}
}
%>

<% if (options.langDir) { %>
export const ASYNC_LOCALES = {
<%= Array.from(
new Set(options.locales.map(l => `'${l.file}': () => import('../${relativeToBuild(options.langDir, l.file)}' /* webpackChunkName: "lang-${l.file}" */)`))
).join(',\n ') %>
}
<% } %>
15 changes: 7 additions & 8 deletions src/templates/utils.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import { LOCALE_CODE_KEY, LOCALE_FILE_KEY, MODULE_NAME } from './options'
import {
LOCALE_CODE_KEY,
LOCALE_FILE_KEY,
MODULE_NAME/* <% if (options.langDir) { %> */,
ASYNC_LOCALES/* <% } %> */
} from './options'

/**
* Asynchronously load messages from translation files
Expand All @@ -17,7 +22,6 @@ export async function loadLanguageAsync (context, locale) {
if (localeObject) {
const file = localeObject[LOCALE_FILE_KEY]
if (file) {
// Hiding template directives from eslint so that parsing doesn't break.
/* <% if (options.langDir) { %> */
let messages
if (process.client) {
Expand All @@ -28,12 +32,7 @@ export async function loadLanguageAsync (context, locale) {
}
if (!messages) {
try {
const langFileModule = await import(
/* webpackChunkName: "lang-[request]" */
/* webpackInclude: /\.(js|ts|json|ya?ml)$/ */
`~/<%= options.langDir %>${file}`
)
const getter = langFileModule.default || langFileModule
const getter = await ASYNC_LOCALES[file]().then(m => m.default || m)
messages = typeof getter === 'function' ? await Promise.resolve(getter(context, locale)) : getter
} catch (error) {
// eslint-disable-next-line no-console
Expand Down

0 comments on commit 9b357da

Please sign in to comment.