Rewrite locale file updating to be more Vue 3 friendly (#5660)

This commit is contained in:
absidue 2024-09-09 14:50:51 +02:00 committed by GitHub
parent c53b117d14
commit b892fb0c30
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 25 additions and 36 deletions

View File

@ -40,17 +40,17 @@ class ProcessLocalesPlugin {
/** @type {(updatedLocales: [string, string][]) => void|null} */
this.notifyLocaleChange = null
if (this.hotReload) {
this.hotReloadScript = readFileSync(`${__dirname}/_hotReloadLocalesScript.js`, 'utf-8')
}
this.loadLocales()
}
/** @param {import('webpack').Compiler} compiler */
apply(compiler) {
const { CachedSource, RawSource } = compiler.webpack.sources;
const { Compilation } = compiler.webpack
const { Compilation, DefinePlugin } = compiler.webpack
new DefinePlugin({
'process.env.HOT_RELOAD_LOCALES': this.hotReload
}).apply(compiler)
compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => {
const IS_DEV_SERVER = !!compiler.watching
@ -136,19 +136,6 @@ class ProcessLocalesPlugin {
compilation.fileDependencies.addAll(this.filePaths)
}
})
compiler.hooks.emit.tap(PLUGIN_NAME, (compilation) => {
if (this.hotReload) {
// Find generated JavaScript output file (e.g. renderer.js or web.js)
// and inject the code snippet that listens for locale updates and replaces vue-i18n's locales
/** @type {string} */
const filename = [...[...compilation.chunks][0].files]
.find(file => file.endsWith('.js'))
compilation.assets[filename]._source._children.push(`\n${this.hotReloadScript}`)
}
})
}
loadLocales() {

View File

@ -1,18 +0,0 @@
const websocket = new WebSocket('ws://localhost:9080/ws')
websocket.onmessage = (event) => {
const message = JSON.parse(event.data)
if (message.type === 'freetube-locale-update') {
const i18n = document.getElementById('app').__vue__.$i18n
for (const [locale, data] of message.data) {
// Only update locale data if it was already loaded
if (i18n.availableLocales.includes(locale)) {
const localeData = JSON.parse(data)
i18n.setLocaleMessage(locale, localeData)
}
}
}
}

View File

@ -50,4 +50,24 @@ export async function loadLocale(locale) {
i18n.setLocaleMessage(locale, data)
}
// Set by _scripts/ProcessLocalesPlugin.js
if (process.env.HOT_RELOAD_LOCALES) {
const websocket = new WebSocket('ws://localhost:9080/ws')
websocket.onmessage = (event) => {
const message = JSON.parse(event.data)
if (message.type === 'freetube-locale-update') {
for (const [locale, data] of message.data) {
// Only update locale data if it was already loaded
if (i18n.availableLocales.includes(locale)) {
const localeData = JSON.parse(data)
i18n.setLocaleMessage(locale, localeData)
}
}
}
}
}
export default i18n