Skip to content

Commit c5d27af

Browse files
authored
Merge pull request #46 from xiCO2k/fix/add-support-for-common-js
fix: Add support for CommonJS Builds
2 parents 63bd3e1 + e132726 commit c5d27af

File tree

8 files changed

+1331
-652
lines changed

8 files changed

+1331
-652
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ For Server Side Rendering the resolve method should not receive a `Promise` and
5454
.use(i18nVue, {
5555
lang: 'pt',
5656
resolve: lang => {
57-
const langs = import.meta.globEager(`../../lang/${lang}.json`);
57+
const langs = import.meta.globEager('../../lang/*.json');
5858
return langs[`../../lang/${lang}.json`].default;
5959
},
6060
})

package-lock.json

Lines changed: 1187 additions & 594 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,29 +14,34 @@
1414
"repository": "https://github.com/xico2k/laravel-vue-i18n",
1515
"license": "MIT",
1616
"description": "allows to connect your `Laravel` Framework localization files with `Vue`.",
17-
"main": "dist/index.js",
17+
"main": "dist/cjs/index.js",
18+
"module": "dist/index.js",
1819
"scripts": {
1920
"watch": "tsc --watch",
2021
"test": "jest",
2122
"coverage": "jest --coverage",
2223
"lint": "prettier -c \"src/**/*.(ts|js|vue)\" --write",
2324
"build:plugins": "tsc -p tsconfig.plugins.json",
2425
"build:client": "tsc -p tsconfig.json",
25-
"build": "npm run build:plugins && npm run build:client",
26+
"build:cjs": "tsc -p tsconfig.commonjs.json && babel dist/cjs/utils/has-php-translations.js --out-file dist/cjs/utils/has-php-translations.js",
27+
"build": "npm run build:plugins && npm run build:client && npm run build:cjs",
2628
"prepare": "npm run build",
2729
"postpublish": "PACKAGE_VERSION=$(cat package.json | grep \\\"version\\\" | head -1 | awk -F: '{ print $2 }' | sed 's/[\",]//g' | tr -d '[[:space:]]') && git tag v$PACKAGE_VERSION && git push --tags"
2830
},
2931
"devDependencies": {
30-
"@babel/preset-env": "^7.18.2",
32+
"@babel/cli": "^7.18.9",
33+
"@babel/core": "^7.18.9",
34+
"@babel/preset-env": "^7.18.9",
3135
"@types/jest": "^27.4.1",
3236
"@vue/babel-plugin-jsx": "^1.1.1",
33-
"@vue/test-utils": "^2.0.0",
37+
"@vue/test-utils": "^2.0.2",
3438
"babel-jest": "^27.5.1",
3539
"babel-plugin-transform-vite-meta-env": "^1.0.3",
3640
"jest": "^27.5.1",
3741
"prettier": "^2.7.1",
42+
"source-map": "^0.7.4",
3843
"ts-jest": "^27.1.3",
39-
"ts-loader": "^9.3.0",
44+
"ts-loader": "^9.3.1",
4045
"typescript": "^4.7.4"
4146
},
4247
"dependencies": {

src/index.ts

Lines changed: 91 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { LanguageJsonFileInterface } from './interfaces/language-json-file'
55
import { ReplacementsInterface } from './interfaces/replacements'
66
import { choose } from './pluralization'
77
import { avoidExceptionOnPromise, avoidException } from './utils/avoid-exceptions'
8+
import { hasPhpTranslations } from './utils/has-php-translations'
89

910
const isServer = typeof window === 'undefined'
1011

@@ -41,6 +42,23 @@ export function isLoaded(lang?: string): boolean {
4142
return loaded.some((row) => row.lang.replace(/[-_]/g, '-') === lang.replace(/[-_]/g, '-'))
4243
}
4344

45+
/**
46+
* Loads the language async.
47+
*/
48+
function loadLanguage(lang: string, dashLangTry: boolean = false): void {
49+
const loadedLang: LanguageInterface = loaded.find((row) => row.lang === lang)
50+
51+
if (loadedLang) {
52+
setLanguage(loadedLang)
53+
54+
return
55+
}
56+
57+
const { default: messages } = resolveLang(options.resolve, lang)
58+
59+
applyLanguage(lang, messages, dashLangTry, loadLanguage)
60+
}
61+
4462
/**
4563
* Loads the language file.
4664
*/
@@ -51,23 +69,37 @@ export function loadLanguageAsync(lang: string, dashLangTry = false): Promise<st
5169
return Promise.resolve(setLanguage(loadedLang))
5270
}
5371

54-
return resolveLang(options.resolve, lang).then(({ default: messages }) => {
55-
if (Object.keys(messages).length < 1) {
56-
if (/[-_]/g.test(lang) && !dashLangTry) {
57-
return loadLanguageAsync(
58-
lang.replace(/[-_]/g, (char) => (char === '-' ? '_' : '-')),
59-
true
60-
)
61-
}
62-
if (lang !== options.fallbackLang) {
63-
return loadLanguageAsync(options.fallbackLang)
64-
}
72+
return resolveLangAsync(options.resolve, lang).then(({ default: messages }) =>
73+
applyLanguage(lang, messages, dashLangTry, loadLanguageAsync)
74+
)
75+
}
76+
77+
/**
78+
* Applies the language data and saves it to the loaded storage.
79+
*/
80+
function applyLanguage(
81+
lang: string,
82+
messages: { [key: string]: string },
83+
dashLangTry: boolean = false,
84+
callable: Function
85+
): string {
86+
if (Object.keys(messages).length < 1) {
87+
if (/[-_]/g.test(lang) && !dashLangTry) {
88+
return callable(
89+
lang.replace(/[-_]/g, (char) => (char === '-' ? '_' : '-')),
90+
true
91+
)
6592
}
6693

67-
const data: LanguageInterface = { lang, messages }
68-
loaded.push(data)
69-
return setLanguage(data)
70-
})
94+
if (lang !== options.fallbackLang) {
95+
return callable(options.fallbackLang)
96+
}
97+
}
98+
99+
const data: LanguageInterface = { lang, messages }
100+
loaded.push(data)
101+
102+
return setLanguage(data)
71103
}
72104

73105
/**
@@ -142,53 +174,58 @@ function setLanguage({ lang, messages }: LanguageInterface): string {
142174
}
143175

144176
/**
145-
* It resolves the language file or data, from direct data, require or Promise.
177+
* It resolves the language file or data, from direct data, syncrone.
146178
*/
147-
async function resolveLang(callable: Function, lang: string): Promise<LanguageJsonFileInterface> {
148-
const hasPhpTranslations =
149-
typeof process !== 'undefined' && process.env?.LARAVEL_VUE_I18N_HAS_PHP
150-
? true
151-
: /** @ts-ignore */
152-
typeof import.meta.env !== 'undefined' && import.meta.env.VITE_LARAVEL_VUE_I18N_HAS_PHP
153-
? true
154-
: false
155-
156-
let data = avoidException(callable, lang)
179+
function resolveLang(
180+
callable: Function,
181+
lang: string,
182+
data: { [key: string]: string } = {}
183+
): LanguageJsonFileInterface {
184+
if (!Object.keys(data).length) {
185+
data = avoidException(callable, lang)
186+
}
157187

158-
if (data instanceof Promise) {
159-
if (hasPhpTranslations) {
160-
const phpLang = await avoidExceptionOnPromise(callable(`php_${lang}`))
161-
const jsonLang = await avoidExceptionOnPromise(data)
162-
163-
return new Promise((resolve) =>
164-
resolve({
165-
default: {
166-
...phpLang,
167-
...jsonLang
168-
}
169-
})
170-
)
188+
if (hasPhpTranslations(isServer)) {
189+
return {
190+
default: {
191+
...data,
192+
...avoidException(callable, `php_${lang}`)
193+
}
171194
}
195+
}
172196

173-
return new Promise(async (resolve) =>
174-
resolve({
175-
default: await avoidExceptionOnPromise(data)
176-
})
177-
)
197+
return { default: data }
198+
}
199+
200+
/**
201+
* It resolves the language file or data, from direct data, require or Promise.
202+
*/
203+
async function resolveLangAsync(callable: Function, lang: string): Promise<LanguageJsonFileInterface> {
204+
let data = avoidException(callable, lang)
205+
206+
if (!(data instanceof Promise)) {
207+
return resolveLang(callable, lang, data)
178208
}
179209

180-
if (hasPhpTranslations) {
210+
if (hasPhpTranslations(isServer)) {
211+
const phpLang = await avoidExceptionOnPromise(callable(`php_${lang}`))
212+
const jsonLang = await avoidExceptionOnPromise(data)
213+
181214
return new Promise((resolve) =>
182215
resolve({
183216
default: {
184-
...data,
185-
...avoidException(callable, `php_${lang}`)
217+
...phpLang,
218+
...jsonLang
186219
}
187220
})
188221
)
189222
}
190223

191-
return new Promise((resolve) => resolve({ default: data }))
224+
return new Promise(async (resolve) =>
225+
resolve({
226+
default: await avoidExceptionOnPromise(data)
227+
})
228+
)
192229
}
193230

194231
/**
@@ -235,6 +272,11 @@ export const i18nVue: Plugin = {
235272
app.config.globalProperties.$t = (key: string, replacements: ReplacementsInterface) => trans(key, replacements)
236273
app.config.globalProperties.$tChoice = (key: string, number: number, replacements: ReplacementsInterface) =>
237274
transChoice(key, number, replacements)
238-
loadLanguageAsync(options.lang || options.fallbackLang)
275+
276+
if (isServer) {
277+
loadLanguage(options.lang || options.fallbackLang)
278+
} else {
279+
loadLanguageAsync(options.lang || options.fallbackLang)
280+
}
239281
}
240282
}

src/utils/has-php-translations.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
export function hasPhpTranslations(isServer: boolean): boolean {
2+
return isServer || checkProcessEnv() || checkImportMeta()
3+
}
4+
5+
function checkProcessEnv(): boolean {
6+
return typeof process !== 'undefined' && process.env?.LARAVEL_VUE_I18N_HAS_PHP ? true : false
7+
}
8+
9+
function checkImportMeta(): boolean {
10+
/** @ts-ignore */
11+
return import.meta.env.VITE_LARAVEL_VUE_I18N_HAS_PHP ? true : false
12+
}

tsconfig.commonjs.json

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
{
2+
"compilerOptions": {
3+
"target": "ES2015",
4+
"module": "commonjs",
5+
"moduleResolution": "node",
6+
"resolveJsonModule": true,
7+
"declaration": true,
8+
"esModuleInterop": true,
9+
"allowSyntheticDefaultImports": true,
10+
"skipDefaultLibCheck": true,
11+
"outDir": "dist/cjs"
12+
},
13+
"include": [
14+
"src/**/*.ts"
15+
],
16+
"exclude": [
17+
"node_modules",
18+
"src/vite.ts",
19+
"src/mix.ts",
20+
"src/loader.ts",
21+
],
22+
"rules": {
23+
"no-console": false
24+
}
25+
}

tsconfig.json

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
11
{
22
"compilerOptions": {
3-
"target": "ESNext",
4-
"module": "ESNext",
3+
"target": "ES2020",
4+
"module": "ES2020",
55
"moduleResolution": "node",
6+
"resolveJsonModule": true,
7+
"declaration": true,
8+
"esModuleInterop": true,
69
"outDir": "dist"
710
},
811
"include": [

tsconfig.plugins.json

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@
1313
"esModuleInterop": true,
1414
"sourceMap": true,
1515
"allowSyntheticDefaultImports": true,
16-
"esModuleInterop": true,
1716
"skipDefaultLibCheck": true
1817
},
1918
"include": [

0 commit comments

Comments
 (0)