monaco-editor-nls-adapter 2.0.0 → 2.1.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
@@ -13,8 +13,10 @@ 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).
@@ -110,6 +112,26 @@ export default defineConfig({
110
112
  });
111
113
  ```
112
114
 
115
+ ### 4. Bundle Optimization (Optional)
116
+
117
+ If you are concerned about bundle size or the "Stat size" reported by bundle analyzers, you can use the **Lite Version**.
118
+
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
+
121
+ ```javascript
122
+ // 1. Import from /lite
123
+ import { setMessages } from 'monaco-editor-nls-adapter/lite';
124
+
125
+ // 2. Manually import ONLY the language you need
126
+ import zhHans from 'monaco-editor-nls-adapter/locales/zh-hans.json';
127
+
128
+ // 3. Initialize BEFORE monaco-editor loads
129
+ setMessages(zhHans, 'zh-hans');
130
+
131
+ // 4. Import monaco-editor as usual
132
+ import * as monaco from 'monaco-editor';
133
+ ```
134
+
113
135
  ## 📖 Usage
114
136
 
115
137
  ### Initialization
@@ -150,10 +172,10 @@ See: [Framework Integration Best Practices (Examples)](./examples/framework-inte
150
172
 
151
173
  | Function | Description |
152
174
  | --- | --- |
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. |
175
+ | `init(locale?: string): boolean` | Synchronous initialization. **Note**: This will trigger the bundler to scan all locales in the directory. |
176
+ | `initAsync(locale?: string): Promise<boolean>` | Asynchronous initialization with dynamic imports. |
155
177
  | `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. |
178
+ | `setMessages(data: object, locale?: string)` | Manually inject translations. Recommended with `./lite` for minimum footprint. |
157
179
  | `vitePlugin(options?: object)` | Vite plugin function. |
158
180
  | `loader: string` | Absolute path to the Webpack loader. |
159
181
 
package/README_zh.md CHANGED
@@ -15,6 +15,9 @@
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)。
@@ -110,6 +113,26 @@ export default defineConfig({
110
113
  });
111
114
  ```
112
115
 
116
+ ### 4. 极致体积优化 (可选)
117
+
118
+ 如果你对打包后的 JS 文件体积非常敏感,或者 bundle analyzer 显示 `monaco-editor-nls-adapter` 的 `Stat size` 过大(这是由于默认入口包含所有语言包的动态引用导致的),可以使用 **Lite 版本**。
119
+
120
+ Lite 版本不具备内置的语言包发现逻辑,需要你手动导入所需的语言 JSON。这样构建工具(Webpack/Vite)只会打包你真正使用的那门语言,而不会扫描整个 `./locales` 目录。
121
+
122
+ ```javascript
123
+ // 1. 从 /lite 入口导入
124
+ import { setMessages } from 'monaco-editor-nls-adapter/lite';
125
+
126
+ // 2. 手动导入特定的语言 JSON (由你自己决定包含哪门语言)
127
+ import zhHans from 'monaco-editor-nls-adapter/locales/zh-hans.json';
128
+
129
+ // 3. 初始化 (必须要在 monaco 加载前运行)
130
+ setMessages(zhHans, 'zh-hans');
131
+
132
+ // 4. 正常使用 monaco-editor
133
+ import * as monaco from 'monaco-editor';
134
+ ```
135
+
113
136
  ## 📖 使用指南
114
137
 
115
138
  ### 初始化
@@ -150,10 +173,10 @@ import * as monaco from 'monaco-editor';
150
173
 
151
174
  | 函数 | 说明 |
152
175
  | --- | --- |
153
- | `init(locale?: string): boolean` | 同步初始化。如果不传参数,尝试探测浏览器语言。返回是否加载成功。 |
154
- | `initAsync(locale?: string): Promise<boolean>` | 异步初始化。利用动态 import 拆分语言包。返回是否加载成功。 |
176
+ | `init(locale?: string): boolean` | 同步初始化。如果不传参数,尝试探测浏览器语言。注意:此方法会导致构建工具引入全量语言包(或触发全量扫描)。 |
177
+ | `initAsync(locale?: string): Promise<boolean>` | 异步初始化。利用动态 import 拆分语言包。 |
155
178
  | `getCurrentLocale(): string` | 获取当前已生效的语言代码。如果是自定义数据,返回 `custom`。 |
156
- | `setMessages(data: object)` | 手动注入翻译字典。格式需符合 Monaco NLS 结构。 |
179
+ | `setMessages(data: object, locale?: string)` | 手动注入翻译字典。建议配合 `./lite` 入口使用以优化体积。 |
157
180
  | `vitePlugin(options?: object)` | Vite 插件函数。 |
158
181
  | `loader: string` | Webpack Loader 的绝对路径。 |
159
182
 
package/index.d.ts CHANGED
@@ -25,15 +25,21 @@ export function init(locale?: LocaleCode | string, force?: boolean): boolean;
25
25
  export function initAsync(locale?: LocaleCode | string, force?: boolean): Promise<boolean>;
26
26
 
27
27
  /**
28
- * 获取当前已生效的语言代码
28
+ * 获取当前已生效的语言代码名称
29
29
  */
30
- export function getCurrentLocale(): string;
30
+ export function getLocaleName(): string;
31
+
32
+ /**
33
+ * 获取当前加载的原始翻译数据
34
+ */
35
+ export function getLocaleData(): Record<string, any> | null;
31
36
 
32
37
  /**
33
38
  * 手动设置翻译数据字典
34
39
  * @param messages 符合 Monaco NLS 格式的 JSON 对象
40
+ * @param locale 语言代码 (可选标识符)
35
41
  */
36
- export function setMessages(messages: Record<string, any>): void;
42
+ export function setMessages(messages: Record<string, any>, locale?: string): void;
37
43
 
38
44
  /**
39
45
  * NLS 代理对象声明
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,27 @@
1
+ const proxy = require('./proxy')
2
+
3
+ /**
4
+ * 获取当前已生效的语言代码
5
+ */
6
+ function getCurrentLocale() {
7
+ return proxy.getLocaleName()
8
+ }
9
+
10
+ /**
11
+ * 手动设置翻译数据字典
12
+ * @param {Object} data 符合 Monaco NLS 格式的 JSON 对象
13
+ * @param {string} locale 语言代码标识 (可选)
14
+ */
15
+ function setMessages(data, locale = 'custom') {
16
+ proxy.setLocaleData(data, locale)
17
+ }
18
+
19
+ module.exports = {
20
+ getCurrentLocale: getCurrentLocale,
21
+ setMessages: setMessages,
22
+ setLocaleData: proxy.setLocaleData,
23
+ proxy: proxy,
24
+ // 插件导出 (仍保留,以便用户可以从 lite 引用所有工具)
25
+ vitePlugin: require('./vite-plugin'),
26
+ loader: __dirname + '/loader.js'
27
+ }
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 逻辑