-
Notifications
You must be signed in to change notification settings - Fork 0
/
generate-loading-script.js
61 lines (49 loc) · 1.58 KB
/
generate-loading-script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
const fs = require('fs')
const path = require('path')
const { forEach } = require('lodash')
const XXH = require('xxhashjs')
const babel = require('@babel/core')
const langDir = path.resolve(__dirname, './public/i18n')
const loadingFilePath = path.resolve(__dirname, './src/loading.js')
const outputDir = path.resolve(__dirname, './docs')
const isProdEnv = process.env.NODE_ENV === 'production'
const storage = {}
function getLanguageList() {
const langs = fs.readdirSync(langDir)
const languageList = {}
forEach(langs, lang => {
const filePath = path.resolve(langDir, lang, 'index.json')
const fileContent = fs.readFileSync(filePath)
languageList[lang] = JSON.parse(String(fileContent))
})
storage.languageList = languageList
}
function getLoadingFileContent() {
const fileContent = fs.readFileSync(loadingFilePath)
storage.fileContent = String(fileContent)
}
function generateLoadingScript() {
getLanguageList()
getLoadingFileContent()
let wrappedContent = `;(function() {
const languages = ${JSON.stringify(storage.languageList)} \n
${storage.fileContent}
})()`
// babel parse
wrappedContent = babel.transformSync(wrappedContent, {
minified: isProdEnv,
comments: !isProdEnv,
configFile: false,
presets: [['@babel/preset-env']],
}).code
const hash = XXH.h32(wrappedContent, 0xabcd).toString(16)
const basename = `loading.${hash}.js`
const filePath = path.resolve(outputDir, `./${basename}`)
fs.writeFileSync(filePath, wrappedContent)
return {
filePath,
basename,
hash,
}
}
module.exports = generateLoadingScript