微信小程序国际化
參考文件:
國際化(微信小程序+TS
微信小程序國際化
https://github.com/wechat-miniprogram/miniprogram-i18n
一、環境目錄
注意:一定要注意項目目錄結構,新建文件夾miniprogram,并把前面新建的文件移到這個目錄中
二、安裝根目錄依賴
在NEW-FAN-CLOCK1 中安裝根目錄依賴
npm i -D gulp @miniprogram-i18n/gulp-i18n-locales @miniprogram-i18n/gulp-i18n-wxml三、新建文件夾minprogram,安裝minprogram依賴
在NEW-FAN-CLOCK1 / minprogram 中安裝依賴
1、初始化倉庫: 一直回車,minprogram中生成package.json文件,即初始化成功,此時即可安裝依賴
2、安裝依賴
npm i -S @miniprogram-i18n/core四、 構建npm
小程序開發工具左上角>工具>構建npm,構建成功之后minprogram中會生成一個miniprogram_npm這個文件夾,這個時候就已經可以使用依賴了
構建中會提示報錯信息:
沒有找到可以構建的 NPM 包,請確認需要參與構建的 npm 都在 miniprogramRoot 目錄內,或配置
project.config.json 的 packNpmManually 和 packNpmRelationList 進行構建
解決方案:添加如下配置
五、新建gulpfile.js 文件
在NEW-FAN-CLOCK1目錄下,新建gulpfile.js 文件,文件內容如下
/* eslint-disable require-jsdoc */ const {src, dest, series} = require('gulp'); const gulpI18nWxml = require('@miniprogram-i18n/gulp-i18n-wxml'); const gulpI18nLocales = require('@miniprogram-i18n/gulp-i18n-locales');function mergeAndGenerateLocales() {return src('miniprogram/i18n/*.json').pipe(gulpI18nLocales({defaultLocale: 'zh-CN', fallbackLocale: 'zh-CN'})).pipe(dest('dist/i18n/')); }function transpileWxml() {return src('miniprogram/**/*.wxml').pipe(gulpI18nWxml({wxsPath: 'miniprogram/i18n/locales.wxs',})).pipe(dest('dist/')); }function copyToDist() {return src(['miniprogram/**/*', '!miniprogram/**/*.wxml', '!miniprogram/i18n/*.json']).pipe(dest('dist/')); }exports.default = series(copyToDist, transpileWxml, mergeAndGenerateLocales);六、i18 文本定義
在miniprogram中新建i18n文件夾,新建json文件,內容為空,必須有一個{}
七、使用
注意Page要修改為I18nPage
<view>{{ t('index') }}</view>
json 文件里會涉及到的中文,一個是TabBar,一個是NavigationBarTitle。沒有辦法在JSON文件中國際化,故使用js去動態設置
八、中英文切換
import { I18nPage } from '@miniprogram-i18n/core' I18nPage({onLoad() {// 語言切換時觸發this.onLocaleChange((locale) => {// 獲取當前語言console.log('current locale:', this.getLocale(), locale)})// 設置中文this.setLocale('zh-CN')},toggleLocale() {// 切換語言this.setLocale(this.getLocale() === 'zh-CN' ? 'en-US' : 'zh-CN')}, })獲取手機系統語言
const systemLang = wx.getAppBaseInfo().language;console.log("手機配置語言",systemLang)/** 根據本地語言設置小程序語言 */i18n.setLocale(systemLang.toLowerCase().includes('zh') ? 'zh-CN' : 'en-US')九、打包編譯
1、配置project.config.js
2、配置package.json
3、打開NEW-FAN-CLOCK1 目錄終端,執行npm run build
到此,微信小程序國際化完成,但是有個很不好的操作,不會自動更新頁面了,每次都需要 npm run build
總結
- 上一篇: Android - 简单的查看APP启动
- 下一篇: WAP、触屏版网站及APP的区别