# node: msg URL: https://generaltranslation.com/zh/docs/node/api/strings/msg.mdx --- title: msg description: msg() 字符串函数的 API 参考文档 --- ## 概述 `msg` 函数用于标记字符串,并将其编码为可翻译内容。 ```js const encodedString = msg('Hello, world!'); ``` 编码后的字符串应传给 [`getMessages`](/docs/node/api/get-messages) 函数,以获取翻译结果。 **编码:** `msg` 会对输入字符串进行编码,因此不能在应用中直接使用。 如果你想恢复原始字符串,需要使用 [`decodeMsg`](#decodemsg) 进行解码。 注意:如果你调用 `msg` 时只传入字符串而不提供任何选项,它返回的仍然是编码后的字符串——而不是原始字符串。 使用 `decodeMsg` 获取原始内容。 ## 解码 [#decodemsg] 要恢复原始字符串,你需要使用 [`decodeMsg`](#decodemsg) 进行解码 ```js import { msg, decodeMsg } from 'gt-node'; const encodedString = msg('Hello, world!'); const decodedString = decodeMsg(encodedString); console.log(decodedString); // "Hello, world!" ``` ## 参考 ### 参数 | 名称 | 类型 | 说明 | | ---------- | ----------------------------------------------------------------------------- | -------------------- | | `content` | `string` | 要编码的字符串内容。 | | `options?` | [`InlineTranslationOptions`](/docs/next/api/types/inline-translation-options) | 用于自定义 `msg` 行为的翻译选项。 | ### 返回值 一个编码后的字符串,其中的插值变量 (如有) 会被替换为其对应的值。 *** ## 行为 ### 生产环境 在 CD 过程中,`msg` 函数中的任何内容都会在应用部署前完成翻译。 这可确保所有区域设置下都能快速加载,但它只能翻译在构建时已知的内容。 生成后,翻译内容会根据你的配置,(1) 存储在 CDN 中,或 (2) 存储在应用的构建输出中。 然后,这些翻译后的内容会被提供给用户。 如果未找到翻译,则会回退为原始内容。 请务必遵循[此处的部署指南](/docs/next/tutorials/quickdeploy)。 ### 开发 在开发环境中,`msg` 函数会按需翻译内容。 这对于快速原型很有帮助,方便你查看应用在不同语言下的显示效果。 请记得在环境中添加 Dev API key,以启用此行为。 在开发环境中按需翻译时,你会看到一定延迟。 除非内容被明确设为按需翻译,否则生产构建中不会出现这种情况。 *** ## 示例 ### 基本用法 你可以使用 `msg` 将字符串标记为可翻译内容。 ```js copy import { msg, getMessages } from 'gt-node'; const greeting = msg('Hello, world!'); const m = await getMessages(); const translated = m(greeting); console.log(translated); // "Hello, world!"(已翻译) ``` 注意:"Hello, world!" 会被翻译成用户的首选语言。 ### 使用变量 [#variables] 你可以向字典中的翻译条目传入变量。 ```js copy import { msg, getMessages } from 'gt-node'; const greeting = msg('Hello, {name}!', { name: 'Alice' }); const m = await getMessages(); const translated = m(greeting); console.log(translated); // "Hello, Alice!"(已翻译) ``` 注意:"Alice" 不会被翻译为用户的首选语言,因为它是一个变量。 ### 使用 ICU 消息格式 `gt-node` 支持 ICU 消息格式,因此你也可以对变量进行格式化。 ```js copy import { msg, getMessages } from 'gt-node'; const encodedString = msg('There are {count, plural, =0 {no items} =1 {one item} other {{count} items}} in the cart', { count: 10 }); const m = await getMessages(); const translated = m(encodedString); console.log(translated); ``` ICU 消息格式是一种功能强大的变量格式化方式。 更多信息,请参阅 [ICU 消息格式文档](https://unicode-org.github.io/icu/userguide/format_parse/messages/)。 *** ## 说明 * `msg` 函数用于将字符串标记为可翻译内容。 * 使用 `msg` 的字符串会在 runtime 之前、即构建过程中完成翻译 (开发环境除外) 。 ## 后续步骤 * 如需了解如何在 runtime 解析翻译后的字符串,请参阅 [`getMessages`](/docs/node/api/get-messages)。