monaco-editor-nls-adapter 2.1.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -21,6 +21,7 @@ Multi-language NLS adapter for Monaco Editor 0.50.0+ (Self-hosted). Bridge the g
21
21
  - **Flexible API**: Advanced interfaces like `getCurrentLocale` and `setMessages` (custom data).
22
22
  - **Cross-Bundler**: Native support for **Webpack** (Loader) and **Vite/Rollup** (Plugin).
23
23
  - **Zero Configuration**: Automatic detection of `pnpm` and monorepo paths out of the box.
24
+ - **Resilient**: Global singleton state for micro-frontends and nested dependency environments.
24
25
  - **Ultra-lightweight**: Redundant test files removed for even faster installation.
25
26
 
26
27
  ## 📦 Supported Frameworks
@@ -112,14 +113,34 @@ export default defineConfig({
112
113
  });
113
114
  ```
114
115
 
115
- ### 4. Bundle Optimization (Optional)
116
+ ### 4. On-demand Packaging (Recommended)
116
117
 
117
- If you are concerned about bundle size or the "Stat size" reported by bundle analyzers, you can use the **Lite Version**.
118
+ By default, the adapter's entry point contains dynamic references that may cause bundlers to include all available locales (~13MB total stat size).
118
119
 
119
- The default entry point uses dynamic `require`/`import` with template strings, which may cause build tools (Webpack/Vite) to scan and include all available locales or report a large "original size." The Lite version eliminates this by providing only the core logic.
120
+ You can use the `languages` option to specify **only** the languages you need. This is easier than the Lite version because it retains the full automation of `init()` and `initAsync()` while significantly reducing the bundle size.
120
121
 
122
+ #### Vite Configuration (`vite.config.js`)
121
123
  ```javascript
122
- // 1. Import from /lite
124
+ vitePlugin({
125
+ languages: ['zh-hans', 'en'] // Only include Simplified Chinese and English
126
+ })
127
+ ```
128
+
129
+ #### Webpack Configuration (`webpack.config.js`)
130
+ ```javascript
131
+ {
132
+ loader: loader,
133
+ options: {
134
+ languages: ['zh-hans', 'ja'] // Only include Simplified Chinese and Japanese
135
+ }
136
+ }
137
+ ```
138
+
139
+ > [!TIP]
140
+ > **Extreme Optimization (Lite Version)**: If you want zero code injection, you can bypass the main entry point entirely and use the Lite version. See below:
141
+
142
+ ```javascript
143
+ // 1. Import from /lite (No dynamic loading logic included)
123
144
  import { setMessages } from 'monaco-editor-nls-adapter/lite';
124
145
 
125
146
  // 2. Manually import ONLY the language you need
@@ -127,9 +148,6 @@ import zhHans from 'monaco-editor-nls-adapter/locales/zh-hans.json';
127
148
 
128
149
  // 3. Initialize BEFORE monaco-editor loads
129
150
  setMessages(zhHans, 'zh-hans');
130
-
131
- // 4. Import monaco-editor as usual
132
- import * as monaco from 'monaco-editor';
133
151
  ```
134
152
 
135
153
  ## 📖 Usage
@@ -174,8 +192,11 @@ See: [Framework Integration Best Practices (Examples)](./examples/framework-inte
174
192
  | --- | --- |
175
193
  | `init(locale?: string): boolean` | Synchronous initialization. **Note**: This will trigger the bundler to scan all locales in the directory. |
176
194
  | `initAsync(locale?: string): Promise<boolean>` | Asynchronous initialization with dynamic imports. |
177
- | `getCurrentLocale(): string` | Returns the currently active locale code. Returns `custom` if set via `setMessages`. |
195
+ | `getLocaleName(): string` | [New] Returns the currently active locale code name (e.g., 'zh-hans'). |
196
+ | `getLocaleData(): object` | [New] Returns the current raw translation dictionary object. |
197
+ | `getCurrentLocale(): string` | Returns the currently active locale (alias for `getLocaleName`). |
178
198
  | `setMessages(data: object, locale?: string)` | Manually inject translations. Recommended with `./lite` for minimum footprint. |
199
+ | `setLocaleData(data: object, locale?: string)` | Alias to `setMessages`. Sets the locale data into the proxy directly. |
179
200
  | `vitePlugin(options?: object)` | Vite plugin function. |
180
201
  | `loader: string` | Absolute path to the Webpack loader. |
181
202
 
package/README_zh.md CHANGED
@@ -22,6 +22,7 @@
22
22
  - **灵活的 API**: 提供 `getCurrentLocale` 和 `setMessages` (自定义数据) 等高级接口。
23
23
  - **跨构建工具支持**: 原生支持 **Webpack** (Loader) 以及 **Vite/Rollup** (Plugin)。
24
24
  - **智能路径探测**: 自动识别 `pnpm` 和 monorepo 路径,**零配置**即可使用。
25
+ - **环境鲁棒性**: 内置全局单例状态管理,支持微前端和多版本依赖嵌套场景。
25
26
  - **轻量化**: 移除了冗余测试文件,发布包体积进一步精简。
26
27
 
27
28
  ## 📦 支持的框架
@@ -113,24 +114,41 @@ export default defineConfig({
113
114
  });
114
115
  ```
115
116
 
116
- ### 4. 极致体积优化 (可选)
117
+ ### 4. 语言包按需打包 (推荐优化方案)
117
118
 
118
- 如果你对打包后的 JS 文件体积非常敏感,或者 bundle analyzer 显示 `monaco-editor-nls-adapter` `Stat size` 过大(这是由于默认入口包含所有语言包的动态引用导致的),可以使用 **Lite 版本**。
119
+ 默认情况下,由于 `index.js` 包含动态引用,构建工具可能会扫描并打包 `./locales` 目录下的所有语言文件(Stat size 较大)。
119
120
 
120
- Lite 版本不具备内置的语言包发现逻辑,需要你手动导入所需的语言 JSON。这样构建工具(Webpack/Vite)只会打包你真正使用的那门语言,而不会扫描整个 `./locales` 目录。
121
+ 你可以通过 `languages` 配置项来指定**仅打包**需要的语言。这比手动使用 Lite 版本更方便,因为它依然保留了 `init()` `initAsync()` 的全自动加载能力,同时大幅减少产物体积。
121
122
 
123
+ #### Vite 配置 (`vite.config.js`)
122
124
  ```javascript
123
- // 1. 从 /lite 入口导入
125
+ vitePlugin({
126
+ languages: ['zh-hans', 'en'] // 最终产物仅包含中、英语言包
127
+ })
128
+ ```
129
+
130
+ #### Webpack 配置 (`webpack.config.js`)
131
+ ```javascript
132
+ {
133
+ loader: loader,
134
+ options: {
135
+ languages: ['zh-hans', 'ja'] // 最终产物仅包含中、日语言包
136
+ }
137
+ }
138
+ ```
139
+
140
+ > [!TIP]
141
+ > **极致优化 (Lite 版本)**: 如果你连按需打包的代码注入也不想要,可以完全绕过 `index.js`,手动导入 JSON 并调用 `setMessages`。详见下文:
142
+
143
+ ```javascript
144
+ // 1. 从 /lite 入口导入 (不含任何动态加载逻辑)
124
145
  import { setMessages } from 'monaco-editor-nls-adapter/lite';
125
146
 
126
- // 2. 手动导入特定的语言 JSON (由你自己决定包含哪门语言)
147
+ // 2. 手动导入特定的语言 JSON
127
148
  import zhHans from 'monaco-editor-nls-adapter/locales/zh-hans.json';
128
149
 
129
150
  // 3. 初始化 (必须要在 monaco 加载前运行)
130
151
  setMessages(zhHans, 'zh-hans');
131
-
132
- // 4. 正常使用 monaco-editor
133
- import * as monaco from 'monaco-editor';
134
152
  ```
135
153
 
136
154
  ## 📖 使用指南
@@ -175,8 +193,11 @@ import * as monaco from 'monaco-editor';
175
193
  | --- | --- |
176
194
  | `init(locale?: string): boolean` | 同步初始化。如果不传参数,尝试探测浏览器语言。注意:此方法会导致构建工具引入全量语言包(或触发全量扫描)。 |
177
195
  | `initAsync(locale?: string): Promise<boolean>` | 异步初始化。利用动态 import 拆分语言包。 |
178
- | `getCurrentLocale(): string` | 获取当前已生效的语言代码。如果是自定义数据,返回 `custom`。 |
196
+ | `getLocaleName(): string` | [新] 获取当前生效的语言代码名称(如 'zh-hans')。 |
197
+ | `getLocaleData(): object` | [新] 获取当前已加载的完整本地化字典对象。 |
198
+ | `getCurrentLocale(): string` | 获取当前已生效的语言代码(`getLocaleName` 的存量别名)。 |
179
199
  | `setMessages(data: object, locale?: string)` | 手动注入翻译字典。建议配合 `./lite` 入口使用以优化体积。 |
200
+ | `setLocaleData(data: object, locale?: string)` | 同 `setMessages`,直接将数据注入代理层。 |
180
201
  | `vitePlugin(options?: object)` | Vite 插件函数。 |
181
202
  | `loader: string` | Webpack Loader 的绝对路径。 |
182
203
 
package/index.d.ts CHANGED
@@ -2,61 +2,80 @@ import { NLSProxy } from './proxy';
2
2
  import monacoNlsPlugin from './vite-plugin';
3
3
 
4
4
  /**
5
- * 支持的语言代码类型
5
+ * 预设的支持语言代码类型 (也可传递任意字符串)
6
+ * Preset of supported locale codes (any string may be used).
6
7
  */
7
8
  export type LocaleCode =
8
- | 'zh-hans' | 'zh-cn' | 'zh-hant' | 'zh-tw'
9
+ | 'zh-hans' | 'zh-cn' | 'zh-hant' | 'zh-tw' | 'zh-hk'
9
10
  | 'en' | 'ja' | 'ko' | 'de' | 'fr' | 'es' | 'it' | 'ru' | 'pl' | 'tr' | 'cs' | 'pt-br';
10
11
 
11
12
  /**
12
- * 初始化 Monaco Editor 的语言包
13
- * @param locale 语言代码,如 'zh-hans'
14
- * @param force 是否强制重新初始化
15
- * @returns 是否加载成功
13
+ * [全量入口] 使用指定的语言代码初始化 Monaco Editor 的本地化。
14
+ * 注意:由于包含动态 require 逻辑,在 Webpack/Vite 环境下可能会导致扫描并打包全量语言 JSON。
15
+ * [Full Entry] Initialize Monaco Editor localization with a specific locale.
16
+ * WARNING: Uses dynamic require, which may bundle all locales in development/production.
17
+ *
18
+ * @param locale 语言代码 (如 'zh-hans') / Locale code identifier.
19
+ * @param force 是否强制重新初始化 / Force re-initialization.
20
+ * @returns 是否加载成功 / Success status.
16
21
  */
17
22
  export function init(locale?: LocaleCode | string, force?: boolean): boolean;
18
23
 
19
24
  /**
20
- * 异步初始化 Monaco Editor 的语言包
21
- * @param locale 语言代码
22
- * @param force 是否强制重新加载
23
- * @returns 是否加载成功
25
+ * [全量入口] 异步初始化 Monaco Editor 的本地化。
26
+ * 使用动态 import 拆分语言包,有助于减小主包体积。
27
+ * [Full Entry] Asynchronously initialize Monaco localization.
28
+ * Uses dynamic import for chunk splitting.
29
+ *
30
+ * @param locale 语言代码 / Locale code.
31
+ * @param force 是否强制加载 / Force re-load.
32
+ * @returns 是否加载成功 / Success status.
24
33
  */
25
34
  export function initAsync(locale?: LocaleCode | string, force?: boolean): Promise<boolean>;
26
35
 
27
36
  /**
28
- * 获取当前已生效的语言代码名称
37
+ * 获取当前已生效的语言代码名称 / Get the current active locale name.
29
38
  */
30
39
  export function getLocaleName(): string;
31
40
 
32
41
  /**
33
- * 获取当前加载的原始翻译数据
42
+ * 获取当前已生效的语言代码名称 (同 getLocaleName) / Get current locale (alias).
43
+ */
44
+ export function getCurrentLocale(): string;
45
+
46
+ /**
47
+ * 获取当前加载的原始翻译数据字典 / Get current raw translation data.
34
48
  */
35
49
  export function getLocaleData(): Record<string, any> | null;
36
50
 
37
51
  /**
38
- * 手动设置翻译数据字典
39
- * @param messages 符合 Monaco NLS 格式的 JSON 对象
40
- * @param locale 语言代码 (可选标识符)
52
+ * 手动设置翻译数据字典 / Set current translation messages manually.
53
+ * @param messages 符合 Monaco NLS 格式的 JSON 对象 / Dictionary following Monaco NLS format.
54
+ * @param locale 语言代码标识符 (可选) / Locale code identifier.
41
55
  */
42
56
  export function setMessages(messages: Record<string, any>, locale?: string): void;
43
57
 
44
58
  /**
45
- * NLS 代理对象声明
59
+ * 设置当前的本地化字典数据到代理中 / Set locale data into the proxy directly.
60
+ */
61
+ export function setLocaleData(data: Record<string, any>, locale?: string): void;
62
+
63
+ /**
64
+ * NLS 代理对象声明 / The NLS proxy instance.
46
65
  */
47
66
  export const proxy: NLSProxy;
48
67
 
49
68
  /**
50
- * Vite 插件导出
69
+ * Vite 插件导出 / Vite plugin for build-time transformation.
51
70
  */
52
71
  export const vitePlugin: typeof monacoNlsPlugin;
53
72
 
54
73
  /**
55
- * Webpack Loader 绝对路径导出 (用于 webpack.config.js)
74
+ * Webpack Loader 导出 (用于 webpack.config.js) / Webpack loader path.
56
75
  */
57
76
  export const loader: string;
58
77
 
59
- // 重新导出子模块中的类型,方便从主模块引用
78
+ // 重新导出子模块中的类型以便全局引用
60
79
  export { NLSProxy } from './proxy';
61
80
  export { PluginOptions } from './vite-plugin';
62
81
  export { transform } from './transform';
package/lite.js CHANGED
@@ -1,12 +1,26 @@
1
1
  const proxy = require('./proxy')
2
2
 
3
3
  /**
4
- * 获取当前已生效的语言代码
4
+ * 获取当前已生效的语言代码名称 (向后兼容)
5
5
  */
6
6
  function getCurrentLocale() {
7
7
  return proxy.getLocaleName()
8
8
  }
9
9
 
10
+ /**
11
+ * 获取当前已生效的语言名称
12
+ */
13
+ function getLocaleName() {
14
+ return proxy.getLocaleName()
15
+ }
16
+
17
+ /**
18
+ * 获取当前加载的原始翻译数据
19
+ */
20
+ function getLocaleData() {
21
+ return proxy.getLocaleData()
22
+ }
23
+
10
24
  /**
11
25
  * 手动设置翻译数据字典
12
26
  * @param {Object} data 符合 Monaco NLS 格式的 JSON 对象
@@ -17,10 +31,12 @@ function setMessages(data, locale = 'custom') {
17
31
  }
18
32
 
19
33
  module.exports = {
20
- getCurrentLocale: getCurrentLocale,
21
- setMessages: setMessages,
34
+ getCurrentLocale,
35
+ getLocaleName,
36
+ getLocaleData,
37
+ setMessages,
22
38
  setLocaleData: proxy.setLocaleData,
23
- proxy: proxy,
39
+ proxy,
24
40
  // 插件导出 (仍保留,以便用户可以从 lite 引用所有工具)
25
41
  vitePlugin: require('./vite-plugin'),
26
42
  loader: __dirname + '/loader.js'
package/loader.js CHANGED
@@ -1,11 +1,16 @@
1
1
  const { transform } = require('./transform')
2
+ const { generateLocalesCode } = require('./codegen')
2
3
 
3
4
  /**
4
5
  * Webpack Loader for Monaco Editor NLS Adapter
5
6
  */
6
7
  module.exports = function (source) {
7
- // 极致性能优化:第一层极速过滤
8
- if (!this.resourcePath.endsWith('.js') || this.resourcePath.indexOf('monaco-editor') === -1) {
8
+ const resourcePath = this.resourcePath.replace(/\\/g, '/')
9
+ const isAdapter = resourcePath.endsWith('monaco-editor-nls-adapter/index.js') || resourcePath.endsWith('monaco-editor-nls-adapter/index.ts')
10
+ const isMonaco = resourcePath.indexOf('monaco-editor') !== -1
11
+
12
+ // 1. 第一层过滤:仅处理 monaco-editor 或 适配器自身入口
13
+ if (!isAdapter && !isMonaco) {
9
14
  return source
10
15
  }
11
16
 
@@ -13,18 +18,41 @@ module.exports = function (source) {
13
18
 
14
19
  // 获取 loader options
15
20
  const options = (typeof this.getOptions === 'function') ? this.getOptions() : this.query
16
-
17
- // 使用共享的 transform 逻辑
18
- const result = transform(source, this.resourcePath, options || {})
19
-
20
- // 如果返回包含 SourceMap 的对象,则使用 this.callback 提示 Webpack
21
- if (result && typeof result === 'object') {
22
- if (this.callback) {
23
- this.callback(null, result.code, result.map)
24
- return
21
+ const languages = (options && Array.isArray(options.languages)) ? options.languages : null
22
+
23
+ // 2. 处理适配器自身的 index.js (按需打包语言包)
24
+ if (isAdapter && languages) {
25
+ let newCode = source
26
+
27
+ // 替换同步 require
28
+ const syncCode = generateLocalesCode(languages, false)
29
+ if (syncCode) {
30
+ newCode = newCode.replace(/require\(`\.\/locales\/\$\{targetLocale\}\.json`\)/g, syncCode)
31
+ }
32
+
33
+ // 替换异步 import
34
+ const asyncCode = generateLocalesCode(languages, true)
35
+ if (asyncCode) {
36
+ newCode = newCode.replace(/import\(.*?\`\.\/locales\/\$\{targetLocale\}\.json\`\)/g, asyncCode)
37
+ }
38
+
39
+ return newCode
40
+ }
41
+
42
+ // 3. 处理 Monaco Editor 源代码 (注入本地化逻辑)
43
+ if (isMonaco) {
44
+ const result = transform(source, this.resourcePath, options || {})
45
+
46
+ // 如果返回包含 SourceMap 的对象,则使用 this.callback 提示 Webpack
47
+ if (result && typeof result === 'object') {
48
+ if (this.callback) {
49
+ this.callback(null, result.code, result.map)
50
+ return
51
+ }
52
+ return result.code
25
53
  }
26
- return result.code
54
+ return result
27
55
  }
28
56
 
29
- return result
57
+ return source
30
58
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "monaco-editor-nls-adapter",
3
- "version": "2.1.0",
3
+ "version": "2.2.0",
4
4
  "description": "Multi-language NLS adapter for Monaco Editor 0.50.0+ (Self-hosted)",
5
5
  "main": "index.js",
6
6
  "module": "index.js",
package/proxy.js CHANGED
@@ -3,9 +3,12 @@
3
3
  * 此文件通过注入 path 参数,替代了对原本 'monaco-editor-nls/vscode-nls' 的内部依赖方式。
4
4
  */
5
5
 
6
- // 状态变量,记录当前的语言数据和代码
7
- let CURRENT_LOCALE_DATA = null
8
- let CURRENT_LOCALE_NAME = ''
6
+ // 使用全局对象存储状态,确保在多实例或多版本共存时(如多版本依赖嵌套)状态依然同步
7
+ const globalObj = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== 'undefined' ? window : global)
8
+ globalObj.__MONACO_NLS_ADAPTER_STATE__ = globalObj.__MONACO_NLS_ADAPTER_STATE__ || { data: null, name: '' }
9
+
10
+ // 辅助访问器
11
+ const getState = () => globalObj.__MONACO_NLS_ADAPTER_STATE__
9
12
 
10
13
  // 提前编译正则表达式以提升运行时性能
11
14
  const FORMAT_REGEX = /\{(\d+)\}/g
@@ -34,9 +37,10 @@ function _format(message, args) {
34
37
  */
35
38
  function localize(path, data, defaultMessage, ...args) {
36
39
  const key = (data && typeof data === 'object') ? data.key : data
40
+ const state = getState()
37
41
 
38
42
  // 优化点:使用可选链或短路评估快速定位翻译
39
- const fileData = (CURRENT_LOCALE_DATA && CURRENT_LOCALE_DATA[path])
43
+ const fileData = (state.data && state.data[path])
40
44
  const message = fileData ? fileData[key] : undefined
41
45
 
42
46
  // 强化回退逻辑:如果翻译为空或未找到,则回退到默认消息
@@ -60,22 +64,23 @@ function localize2(path, data, defaultMessage, ...args) {
60
64
  * @param {string} locale 语言代码
61
65
  */
62
66
  function setLocaleData(data, locale = 'custom') {
63
- CURRENT_LOCALE_DATA = data
64
- CURRENT_LOCALE_NAME = locale
67
+ const state = getState()
68
+ state.data = data
69
+ state.name = locale
65
70
  }
66
71
 
67
72
  /**
68
73
  * 获取当前已加载的完整字典数据
69
74
  */
70
75
  function getLocaleData() {
71
- return CURRENT_LOCALE_DATA
76
+ return getState().data
72
77
  }
73
78
 
74
79
  /**
75
80
  * 获取当前生效的语言名称
76
81
  */
77
82
  function getLocaleName() {
78
- return CURRENT_LOCALE_NAME
83
+ return getState().name
79
84
  }
80
85
 
81
86
  // 以下为适配 monaco-editor 内部调用的兼容性 Shim 函数
package/transform.js CHANGED
@@ -2,13 +2,13 @@ const MagicString = require('magic-string')
2
2
 
3
3
  let CACHED_MONACO_ROOT = null
4
4
 
5
+ // 提前编译正则表达式以提升运行时性能
6
+ const NLS_IMPORT_REGEX = /(import\s+.*?\s+from\s+['"])(.*?\/nls\.js)(['"])/g
7
+ const NLS_REQUIRE_REGEX = /(require\(['"])(.*?\/nls\.js)(['"]\))/g
8
+ const LOCALIZE_REGEX = /nls\.localize(\d?)\(/g
9
+
5
10
  /**
6
11
  * 转换 Monaco Editor 源代码以注入本地化路径
7
- * @param {string} source 源代码内容
8
- * @param {string} id 文件路径 (resourcePath 或 vite id)
9
- * @param {Object} options 配置项
10
- * @param {string} options.monacoPath 匹配 Monaco Editor 的路径片段,默认为 'monaco-editor/esm'
11
- * @returns {Object|string} 转换后的对象 { code, map } 或原始字符串
12
12
  */
13
13
  function transform(source, id, options = {}) {
14
14
  // 统一路径分隔符
package/vite-plugin.js CHANGED
@@ -1,25 +1,50 @@
1
1
  const { transform } = require('./transform')
2
+ const { generateLocalesCode } = require('./codegen')
2
3
 
3
4
  /**
4
5
  * Vite Plugin for Monaco Editor NLS Adapter
5
6
  * @param {Object} options 插件配置
6
7
  * @param {string} options.monacoPath 匹配 Monaco Editor ESM 路径的特征字符串,默认为 'monaco-editor/esm'
8
+ * @param {string[]} options.languages 需要包含的语言包列表 (如 ['zh-hans', 'en'])。不传则全量打包。
7
9
  */
8
10
  function monacoNlsPlugin(options = {}) {
9
11
  const monacoRoot = options.monacoPath || 'monaco-editor/esm'
10
-
12
+ const languages = Array.isArray(options.languages) ? options.languages : null
13
+
11
14
  return {
12
15
  name: 'vite-plugin-monaco-nls-adapter',
13
16
  enforce: 'pre',
14
17
  transform(code, id) {
15
- // 极致性能优化:第一层极速过滤,避免非目标文件的正则与替换开销
16
- if (!id.endsWith('.js') || id.indexOf('monaco-editor') === -1) return
18
+ if (!id.endsWith('.js')) return
17
19
 
18
20
  // 统一路径格式
19
21
  const normalizedId = id.replace(/\\/g, '/')
20
-
21
- // 快速过滤非目标文件 (进一步细化)
22
- if (normalizedId.includes(monacoRoot)) {
22
+
23
+ // 1. 处理适配器自身的 index.js (按需打包语言包)
24
+ if (languages && (normalizedId.endsWith('monaco-editor-nls-adapter/index.js') || normalizedId.endsWith('monaco-editor-nls-adapter/index.ts'))) {
25
+ let newCode = code
26
+
27
+ // 替换同步 require
28
+ const syncCode = generateLocalesCode(languages, false)
29
+ if (syncCode) {
30
+ newCode = newCode.replace(/require\(`\.\/locales\/\$\{targetLocale\}\.json`\)/g, syncCode)
31
+ }
32
+
33
+ // 替换异步 import
34
+ const asyncCode = generateLocalesCode(languages, true)
35
+ if (asyncCode) {
36
+ // 注意:index.js 中的 import 是带注释的: import(/* webpackChunkName: "nls-[request]" */ `./locales/${targetLocale}.json`)
37
+ newCode = newCode.replace(/import\(.*?\`\.\/locales\/\$\{targetLocale\}\.json\`\)/g, asyncCode)
38
+ }
39
+
40
+ return {
41
+ code: newCode,
42
+ map: null // 对于这种简单的替换,暂不生成 sourcemap 以保持性能
43
+ }
44
+ }
45
+
46
+ // 2. 处理 Monaco Editor 源代码 (注入本地化逻辑)
47
+ if (normalizedId.indexOf('monaco-editor') !== -1 && normalizedId.includes(monacoRoot)) {
23
48
  const result = transform(code, id, options)
24
49
 
25
50
  // 如果 transform 返回的是对象 ({ code, map }),直接返回