monaco-editor-nls-adapter 2.0.0 → 2.1.1

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
@@ -13,12 +13,15 @@ Multi-language NLS adapter for Monaco Editor 0.50.0+ (Self-hosted). Bridge the g
13
13
 
14
14
  - **Self-hosted Locales**: No external CDN dependencies; all language data is bundled locally.
15
15
  - **Monaco 0.50.0+ Ready**: Fully compatible with the latest internal NLS signatures of Monaco Editor.
16
- - **SourceMap Support**: Powered by `magic-string` for accurate source-to-bundle mapping and worry-free debugging.
17
- - **Zero-Config Lazy Loading**: Support for asynchronous initialization with Webpack/Vite chunk splitting.
16
+ - **SourceMap Support**: Powered by `magic-string` for accurate source-to-bundle mapping.
17
+ - **Ultra-Optimized (Mini & Lite)**:
18
+ - **JSON Minification**: All locale files are pre-minified, reducing the stat size by ~15%.
19
+ - **Slim/Lite Export**: Use `./lite` for a zero-bloat experience with no dynamic scanning.
18
20
  - **TypeScript Support**: First-class TS definitions for an excellent developer experience.
19
21
  - **Flexible API**: Advanced interfaces like `getCurrentLocale` and `setMessages` (custom data).
20
22
  - **Cross-Bundler**: Native support for **Webpack** (Loader) and **Vite/Rollup** (Plugin).
21
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.
22
25
  - **Ultra-lightweight**: Redundant test files removed for even faster installation.
23
26
 
24
27
  ## 📦 Supported Frameworks
@@ -110,6 +113,26 @@ export default defineConfig({
110
113
  });
111
114
  ```
112
115
 
116
+ ### 4. Bundle Optimization (Optional)
117
+
118
+ If you are concerned about bundle size or the "Stat size" reported by bundle analyzers, you can use the **Lite Version**.
119
+
120
+ 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.
121
+
122
+ ```javascript
123
+ // 1. Import from /lite
124
+ import { setMessages } from 'monaco-editor-nls-adapter/lite';
125
+
126
+ // 2. Manually import ONLY the language you need
127
+ import zhHans from 'monaco-editor-nls-adapter/locales/zh-hans.json';
128
+
129
+ // 3. Initialize BEFORE monaco-editor loads
130
+ setMessages(zhHans, 'zh-hans');
131
+
132
+ // 4. Import monaco-editor as usual
133
+ import * as monaco from 'monaco-editor';
134
+ ```
135
+
113
136
  ## 📖 Usage
114
137
 
115
138
  ### Initialization
@@ -150,10 +173,13 @@ See: [Framework Integration Best Practices (Examples)](./examples/framework-inte
150
173
 
151
174
  | Function | Description |
152
175
  | --- | --- |
153
- | `init(locale?: string): boolean` | Synchronous initialization. Tries to detect browser language if omitted. Returns success status. |
154
- | `initAsync(locale?: string): Promise<boolean>` | Asynchronous initialization with dynamic imports. Returns success status. |
155
- | `getCurrentLocale(): string` | Returns the currently active locale code. Returns `custom` if set via `setMessages`. |
156
- | `setMessages(data: object)` | Manually inject translation data. Must follow Monaco's NLS structure. |
176
+ | `init(locale?: string): boolean` | Synchronous initialization. **Note**: This will trigger the bundler to scan all locales in the directory. |
177
+ | `initAsync(locale?: string): Promise<boolean>` | Asynchronous initialization with dynamic imports. |
178
+ | `getLocaleName(): string` | [New] Returns the currently active locale code name (e.g., 'zh-hans'). |
179
+ | `getLocaleData(): object` | [New] Returns the current raw translation dictionary object. |
180
+ | `getCurrentLocale(): string` | Returns the currently active locale (alias for `getLocaleName`). |
181
+ | `setMessages(data: object, locale?: string)` | Manually inject translations. Recommended with `./lite` for minimum footprint. |
182
+ | `setLocaleData(data: object, locale?: string)` | Alias to `setMessages`. Sets the locale data into the proxy directly. |
157
183
  | `vitePlugin(options?: object)` | Vite plugin function. |
158
184
  | `loader: string` | Absolute path to the Webpack loader. |
159
185
 
package/README_zh.md CHANGED
@@ -15,10 +15,14 @@
15
15
  - **适配 Monaco 0.50.0+**: 完全兼容 Monaco Editor 最新的内部 NLS 调用签名。
16
16
  - **性能优化 (懒加载)**: 通过 Webpack/Vite 的动态导入实现按需分包加载。
17
17
  - **SourceMap 支持**: 基于 `magic-string` 实现转换后的精准还原,调试无忧。
18
+ - **极致优化 (Mini & Lite)**:
19
+ - **内置 JSON 压缩**: 所有语言包均已移除空格,Stat size 减少约 15%。
20
+ - **Slim/Lite 导出**: 提供 `./lite` 入口,不包含动态加载逻辑,可实现 **0 冗余** 打包。
18
21
  - **TypeScript 支持**: 完善的类型定义,为开发提供极佳的智能感知。
19
22
  - **灵活的 API**: 提供 `getCurrentLocale` 和 `setMessages` (自定义数据) 等高级接口。
20
23
  - **跨构建工具支持**: 原生支持 **Webpack** (Loader) 以及 **Vite/Rollup** (Plugin)。
21
24
  - **智能路径探测**: 自动识别 `pnpm` 和 monorepo 路径,**零配置**即可使用。
25
+ - **环境鲁棒性**: 内置全局单例状态管理,支持微前端和多版本依赖嵌套场景。
22
26
  - **轻量化**: 移除了冗余测试文件,发布包体积进一步精简。
23
27
 
24
28
  ## 📦 支持的框架
@@ -110,6 +114,26 @@ export default defineConfig({
110
114
  });
111
115
  ```
112
116
 
117
+ ### 4. 极致体积优化 (可选)
118
+
119
+ 如果你对打包后的 JS 文件体积非常敏感,或者 bundle analyzer 显示 `monaco-editor-nls-adapter` 的 `Stat size` 过大(这是由于默认入口包含所有语言包的动态引用导致的),可以使用 **Lite 版本**。
120
+
121
+ Lite 版本不具备内置的语言包发现逻辑,需要你手动导入所需的语言 JSON。这样构建工具(Webpack/Vite)只会打包你真正使用的那门语言,而不会扫描整个 `./locales` 目录。
122
+
123
+ ```javascript
124
+ // 1. 从 /lite 入口导入
125
+ import { setMessages } from 'monaco-editor-nls-adapter/lite';
126
+
127
+ // 2. 手动导入特定的语言 JSON (由你自己决定包含哪门语言)
128
+ import zhHans from 'monaco-editor-nls-adapter/locales/zh-hans.json';
129
+
130
+ // 3. 初始化 (必须要在 monaco 加载前运行)
131
+ setMessages(zhHans, 'zh-hans');
132
+
133
+ // 4. 正常使用 monaco-editor
134
+ import * as monaco from 'monaco-editor';
135
+ ```
136
+
113
137
  ## 📖 使用指南
114
138
 
115
139
  ### 初始化
@@ -150,10 +174,13 @@ import * as monaco from 'monaco-editor';
150
174
 
151
175
  | 函数 | 说明 |
152
176
  | --- | --- |
153
- | `init(locale?: string): boolean` | 同步初始化。如果不传参数,尝试探测浏览器语言。返回是否加载成功。 |
154
- | `initAsync(locale?: string): Promise<boolean>` | 异步初始化。利用动态 import 拆分语言包。返回是否加载成功。 |
155
- | `getCurrentLocale(): string` | 获取当前已生效的语言代码。如果是自定义数据,返回 `custom`。 |
156
- | `setMessages(data: object)` | 手动注入翻译字典。格式需符合 Monaco 的 NLS 结构。 |
177
+ | `init(locale?: string): boolean` | 同步初始化。如果不传参数,尝试探测浏览器语言。注意:此方法会导致构建工具引入全量语言包(或触发全量扫描)。 |
178
+ | `initAsync(locale?: string): Promise<boolean>` | 异步初始化。利用动态 import 拆分语言包。 |
179
+ | `getLocaleName(): string` | [新] 获取当前生效的语言代码名称(如 'zh-hans')。 |
180
+ | `getLocaleData(): object` | [新] 获取当前已加载的完整本地化字典对象。 |
181
+ | `getCurrentLocale(): string` | 获取当前已生效的语言代码(`getLocaleName` 的存量别名)。 |
182
+ | `setMessages(data: object, locale?: string)` | 手动注入翻译字典。建议配合 `./lite` 入口使用以优化体积。 |
183
+ | `setLocaleData(data: object, locale?: string)` | 同 `setMessages`,直接将数据注入代理层。 |
157
184
  | `vitePlugin(options?: object)` | Vite 插件函数。 |
158
185
  | `loader: string` | Webpack Loader 的绝对路径。 |
159
186
 
package/index.d.ts CHANGED
@@ -2,55 +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.
38
+ */
39
+ export function getLocaleName(): string;
40
+
41
+ /**
42
+ * 获取当前已生效的语言代码名称 (同 getLocaleName) / Get current locale (alias).
29
43
  */
30
44
  export function getCurrentLocale(): string;
31
45
 
32
46
  /**
33
- * 手动设置翻译数据字典
34
- * @param messages 符合 Monaco NLS 格式的 JSON 对象
47
+ * 获取当前加载的原始翻译数据字典 / Get current raw translation data.
48
+ */
49
+ export function getLocaleData(): Record<string, any> | null;
50
+
51
+ /**
52
+ * 手动设置翻译数据字典 / Set current translation messages manually.
53
+ * @param messages 符合 Monaco NLS 格式的 JSON 对象 / Dictionary following Monaco NLS format.
54
+ * @param locale 语言代码标识符 (可选) / Locale code identifier.
55
+ */
56
+ export function setMessages(messages: Record<string, any>, locale?: string): void;
57
+
58
+ /**
59
+ * 设置当前的本地化字典数据到代理中 / Set locale data into the proxy directly.
35
60
  */
36
- export function setMessages(messages: Record<string, any>): void;
61
+ export function setLocaleData(data: Record<string, any>, locale?: string): void;
37
62
 
38
63
  /**
39
- * NLS 代理对象声明
64
+ * NLS 代理对象声明 / The NLS proxy instance.
40
65
  */
41
66
  export const proxy: NLSProxy;
42
67
 
43
68
  /**
44
- * Vite 插件导出
69
+ * Vite 插件导出 / Vite plugin for build-time transformation.
45
70
  */
46
71
  export const vitePlugin: typeof monacoNlsPlugin;
47
72
 
48
73
  /**
49
- * Webpack Loader 绝对路径导出 (用于 webpack.config.js)
74
+ * Webpack Loader 导出 (用于 webpack.config.js) / Webpack loader path.
50
75
  */
51
76
  export const loader: string;
52
77
 
53
- // 重新导出子模块中的类型,方便从主模块引用
78
+ // 重新导出子模块中的类型以便全局引用
54
79
  export { NLSProxy } from './proxy';
55
80
  export { PluginOptions } from './vite-plugin';
56
81
  export { transform } from './transform';
package/index.js CHANGED
@@ -1,4 +1,5 @@
1
- const proxy = require('./proxy')
1
+ const lite = require('./lite')
2
+ const proxy = lite.proxy
2
3
 
3
4
  /**
4
5
  * 语言映射字典,用于将常见的浏览器语言代码还原为本包中支持的代码。
@@ -29,58 +30,49 @@ const LOCALE_MAP = {
29
30
  'pt-br': 'pt-br'
30
31
  }
31
32
 
32
- let CURRENT_LOCALE = ''
33
33
  let IS_LOADING = false
34
34
 
35
35
  /**
36
36
  * 使用指定的语言代码初始化 Monaco Editor 的本地化。
37
- * 此方法会从本地 /locales 目录加载 JSON 数据。
38
- * @param {string} locale 语言代码 (例如 'zh-hans', 'ja', 'ko')。如果不传,将尝试检测浏览器语言。
39
- * @param {boolean} force 是否强制重新初始化,即使语言相同。
37
+ * 此方法使用同步 require,会触发构建工具打包所有相关 JSON
38
+ * @param {string} locale 语言代码
39
+ * @param {boolean} force 是否强制重新初始化
40
40
  */
41
41
  function init(locale, force = false) {
42
- // SSR 环境安全检查
43
42
  const isBrowser = typeof window !== 'undefined' && typeof navigator !== 'undefined'
44
-
45
- // 如果没有传递 locale,尝试从浏览器环境获取
46
43
  if (!locale && isBrowser) {
47
44
  locale = navigator.language || navigator.userLanguage
48
45
  }
49
46
 
50
- // 小写化并查找映射
51
47
  let targetLocale = (locale || 'zh-hans').toLowerCase()
52
48
  if (LOCALE_MAP[targetLocale]) {
53
49
  targetLocale = LOCALE_MAP[targetLocale]
54
50
  }
55
51
 
56
- // 幂等检查:如果已经加载过该语言且非强制,则直接返回
57
- if (CURRENT_LOCALE === targetLocale && !force) {
52
+ if (lite.getCurrentLocale() === targetLocale && !force) {
58
53
  return true
59
54
  }
60
55
 
61
56
  try {
57
+ // 这里的动态 require 是导致全量打包的主要原因,若需精简请改用 lite.setMessages()
62
58
  const data = require(`./locales/${targetLocale}.json`)
63
- proxy.setLocaleData(data)
64
- CURRENT_LOCALE = targetLocale
59
+ lite.setMessages(data, targetLocale)
65
60
  return true
66
61
  } catch (e) {
67
62
  if (isBrowser) {
68
- console.warn(`[monaco-editor-nls-adapter] 无法加载本地语言包: ${targetLocale}。回退到默认设置。`, e)
63
+ console.warn(`[monaco-editor-nls-adapter] 无法加载本地语言包: ${targetLocale}`, e)
69
64
  }
70
65
  return false
71
66
  }
72
67
  }
73
68
 
74
69
  /**
75
- * 异步初始化 Monaco Editor 的本地化。
76
- * 使用动态 import(),允许 Webpack 将语言包拆分为独立的 chunk。
77
- * @param {string} locale 语言代码。
78
- * @param {boolean} force 是否强制重新加载。
79
- * @returns {Promise<boolean>}
70
+ * 异步加载语言包。
71
+ * @param {string} locale 语言代码
72
+ * @param {boolean} force 是否强制重新初始化
80
73
  */
81
74
  async function initAsync(locale, force = false) {
82
75
  const isBrowser = typeof window !== 'undefined' && typeof navigator !== 'undefined'
83
-
84
76
  if (!locale && isBrowser) {
85
77
  locale = navigator.language || navigator.userLanguage
86
78
  }
@@ -90,7 +82,7 @@ async function initAsync(locale, force = false) {
90
82
  targetLocale = LOCALE_MAP[targetLocale]
91
83
  }
92
84
 
93
- if (CURRENT_LOCALE === targetLocale && !force) {
85
+ if (lite.getCurrentLocale() === targetLocale && !force) {
94
86
  return true
95
87
  }
96
88
 
@@ -98,14 +90,12 @@ async function initAsync(locale, force = false) {
98
90
  IS_LOADING = true
99
91
 
100
92
  try {
101
- // 使用动态 import 实现懒加载,并添加 Webpack 魔术注释以优化分包命名
102
93
  const module = await import(/* webpackChunkName: "nls-[request]" */ `./locales/${targetLocale}.json`)
103
- proxy.setLocaleData(module.default || module)
104
- CURRENT_LOCALE = targetLocale
94
+ lite.setMessages(module.default || module, targetLocale)
105
95
  return true
106
96
  } catch (e) {
107
97
  if (isBrowser) {
108
- console.warn(`[monaco-editor-nls-adapter] 无法异步加载语言包: ${targetLocale}。`, e)
98
+ console.warn(`[monaco-editor-nls-adapter] 无法异步加载语言包: ${targetLocale}`, e)
109
99
  }
110
100
  return false
111
101
  } finally {
@@ -113,30 +103,8 @@ async function initAsync(locale, force = false) {
113
103
  }
114
104
  }
115
105
 
116
- /**
117
- * 获取当前已生效的语言代码
118
- */
119
- function getCurrentLocale() {
120
- return CURRENT_LOCALE
121
- }
122
-
123
- /**
124
- * 手动设置翻译数据字典
125
- * @param {Object} data 符合 Monaco NLS 格式的 JSON 对象
126
- */
127
- function setMessages(data) {
128
- proxy.setLocaleData(data)
129
- CURRENT_LOCALE = 'custom'
130
- }
131
-
132
106
  module.exports = {
107
+ ...lite,
133
108
  init: init,
134
- initAsync: initAsync,
135
- getCurrentLocale: getCurrentLocale,
136
- setMessages: setMessages,
137
- setLocaleData: proxy.setLocaleData, // 向后兼容
138
- proxy: proxy,
139
- // 插件导出 (便于在 config 文件中使用)
140
- vitePlugin: require('./vite-plugin'),
141
- loader: __dirname + '/loader.js'
109
+ initAsync: initAsync
142
110
  }
package/lite.js ADDED
@@ -0,0 +1,43 @@
1
+ const proxy = require('./proxy')
2
+
3
+ /**
4
+ * 获取当前已生效的语言代码名称 (向后兼容)
5
+ */
6
+ function getCurrentLocale() {
7
+ return proxy.getLocaleName()
8
+ }
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
+
24
+ /**
25
+ * 手动设置翻译数据字典
26
+ * @param {Object} data 符合 Monaco NLS 格式的 JSON 对象
27
+ * @param {string} locale 语言代码标识 (可选)
28
+ */
29
+ function setMessages(data, locale = 'custom') {
30
+ proxy.setLocaleData(data, locale)
31
+ }
32
+
33
+ module.exports = {
34
+ getCurrentLocale,
35
+ getLocaleName,
36
+ getLocaleData,
37
+ setMessages,
38
+ setLocaleData: proxy.setLocaleData,
39
+ proxy,
40
+ // 插件导出 (仍保留,以便用户可以从 lite 引用所有工具)
41
+ vitePlugin: require('./vite-plugin'),
42
+ loader: __dirname + '/loader.js'
43
+ }
package/loader.js CHANGED
@@ -4,9 +4,14 @@ const { transform } = require('./transform')
4
4
  * Webpack Loader for Monaco Editor NLS Adapter
5
5
  */
6
6
  module.exports = function (source) {
7
+ // 极致性能优化:第一层极速过滤
8
+ if (!this.resourcePath.endsWith('.js') || this.resourcePath.indexOf('monaco-editor') === -1) {
9
+ return source
10
+ }
11
+
7
12
  if (this.cacheable) this.cacheable()
8
13
 
9
- // 获取 loader options (Webpack 5 推荐 this.getOptions)
14
+ // 获取 loader options
10
15
  const options = (typeof this.getOptions === 'function') ? this.getOptions() : this.query
11
16
 
12
17
  // 使用共享的 transform 逻辑