-
Notifications
You must be signed in to change notification settings - Fork 377
/
index.ts
96 lines (81 loc) · 2.76 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import { getConfig } from "@lingui/conf"
import {
createCompiledCatalog,
getCatalogs,
getCatalogForFile,
getCatalogDependentFiles,
} from "@lingui/cli/api"
import path from "path"
import type { Plugin } from "vite"
const fileRegex = /(\.po|\?lingui)$/
type LinguiConfigOpts = {
cwd?: string
configPath?: string
skipValidation?: boolean
}
export function lingui(linguiConfig: LinguiConfigOpts = {}): Plugin[] {
const config = getConfig(linguiConfig)
return [
{
name: "vite-plugin-lingui-report-macro-error",
enforce: "pre",
resolveId(id) {
if (id.includes("@lingui/macro")) {
throw new Error(
`The macro you imported from "@lingui/macro" is being executed outside the context of compilation. \n` +
`This indicates that you don't have the "babel-plugin-macros" or "@lingui/swc-plugin" configured correctly. ` +
`Please see the documentation for how to configure Vite with Lingui correctly: ` +
"https://lingui.dev/tutorials/setup-vite"
)
}
},
},
{
name: "vite-plugin-lingui",
config: (config) => {
// https://github.com/lingui/js-lingui/issues/1464
if (!config.optimizeDeps) {
config.optimizeDeps = {}
}
config.optimizeDeps.exclude = config.optimizeDeps.exclude || []
config.optimizeDeps.exclude.push("@lingui/macro")
},
async transform(src, id) {
if (fileRegex.test(id)) {
id = id.split("?")[0]
const catalogRelativePath = path.relative(config.rootDir, id)
const fileCatalog = getCatalogForFile(
catalogRelativePath,
await getCatalogs(config)
)
if (!fileCatalog) {
throw new Error(
`Requested resource ${catalogRelativePath} is not matched to any of your catalogs paths specified in "lingui.config".
Resource: ${id}
Your catalogs:
${config.catalogs.map((c) => c.path).join("\n")}
Please check that catalogs.path is filled properly.\n`
)
}
const { locale, catalog } = fileCatalog
const dependency = await getCatalogDependentFiles(catalog, locale)
dependency.forEach((file) => this.addWatchFile(file))
const messages = await catalog.getTranslations(locale, {
fallbackLocales: config.fallbackLocales,
sourceLocale: config.sourceLocale,
})
const compiled = createCompiledCatalog(locale, messages, {
strict: false,
namespace: "es",
pseudoLocale: config.pseudoLocale,
})
return {
code: compiled,
map: null, // provide source map if available
}
}
},
},
]
}
export default lingui