From 9b357da38049c62c9f05710406f91a4b3c59b87a Mon Sep 17 00:00:00 2001 From: Ahad Birang Date: Thu, 4 Mar 2021 23:44:58 +0330 Subject: [PATCH] refactor: add Vite compatibility when lazy loading (#1084) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Rafał Chłodnicki Co-authored-by: Pooya Parsa --- src/index.js | 5 +++++ src/templates/options.js | 8 ++++++++ src/templates/utils.js | 15 +++++++-------- 3 files changed, 20 insertions(+), 8 deletions(-) diff --git a/src/index.js b/src/index.js index b8313655a..e72d4a07b 100644 --- a/src/index.js +++ b/src/index.js @@ -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. diff --git a/src/templates/options.js b/src/templates/options.js index a904a3c3d..329d2c424 100644 --- a/src/templates/options.js +++ b/src/templates/options.js @@ -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 ') %> +} +<% } %> diff --git a/src/templates/utils.js b/src/templates/utils.js index b5a95cb22..084b31e2e 100755 --- a/src/templates/utils.js +++ b/src/templates/utils.js @@ -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 @@ -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) { @@ -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