场景
在做多语言的时候,一般是需要本地写json,然后本地加载。
本地书写配置的弊端:
- 在实际使用中配置文件会不断变大,哪个code还在使用,哪个不用了,不容易维护;
- 在修改多语言时,需要修改代码,重新打包发布;
- 书写时,同一模块同一个语义可能重复定义;
- 书写时,书写文件和定义文件来回切换,开发效率底;
- 书写时,得去不重复定义code,想code的命名。
思维导图

实现
使用webpack compilation.rebuildModule方法重新构建模块
compiler.hooks.compilation.tap(this.constructor.name, (compilation) => {compilation.hooks.finishModules.tapAsync(this.constructor.name, (modules, callback) => {const src = this.i18nZhConfigFilePath;function matcher(m) {return m.resource && m.resource === src;}const module = Array.from(modules).find(matcher);if (!module) return callback()const content = this.genDefaultData()if (!content) {return callback()}// 清除改文件的构建缓存,非常重要compiler.inputFileSystem.purge(src)compiler.fileTimestamps.set(src, Date.now())compilation.rebuildModule(module, (err) => {callback(err)})})})
