-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
210 lines (192 loc) · 6.9 KB
/
index.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
'use strict'
var fs = require('fs-extra')
var glob = require('glob')
var path = require('path')
var crypto = require('crypto')
var helper = require('./utils/helper')
var log = require('./utils/log')
class RubickI18nWebpackPlugin {
constructor(options) {
options = options || {}
this.isDev = process.env.NODE_ENV !== 'production'
this.entry = options.entry
this.manifestBase = options.manifestBase
this.outputDir = options.outputDir
this.translates = {}
this.assetsToEmit = {}
this.prevTimestamps = {}
this.startTime = Date.now()
this.fileDependencies = []
this.localsPrefix = ['zh_cn', 'en']
this.localsPrefix.forEach(local => {
this.translates[local] = {}
})
}
apply(compiler) {
const emitDependencies = (compilation, done) => {
// register dependencies at webpack
if (compilation.fileDependencies.add) {
// webpack@4
this.fileDependencies.forEach(compilation.fileDependencies.add, compilation.fileDependencies)
} else {
compilation.fileDependencies = compilation.fileDependencies.concat(this.fileDependencies)
}
this.emitGeneratedFiles(compilation);
return done()
}
const compile = (compilation, done) => {
if (!this.dependenciesUpdated(compilation)) {
return done()
}
this.localsPrefix.forEach(local => {
this.translates[local] = {}
})
this.compileAllEntryFiles(compilation.compiler.outputPath, done)
return undefined
}
// webpack 4 support
if (compiler.hooks) {
compiler.hooks.make.tapAsync('RubickI18nWebpackPlugin', compile)
compiler.hooks.emit.tapAsync('RubickI18nWebpackPlugin', emitDependencies)
} else {
compiler.plugin('make', compile)
compiler.plugin('emit', emitDependencies)
}
}
dependenciesUpdated(compilation) {
// NOTE: fileTimestamps will be an `object` or `Map` depending on the webpack version
const fileTimestamps = compilation.fileTimestamps
const fileNames = fileTimestamps.has ? Array.from(fileTimestamps.keys()) : Object.keys(fileTimestamps)
const changedFiles = fileNames.filter((watchfile) => {
const prevTimestamp = this.prevTimestamps[watchfile]
const nextTimestamp = fileTimestamps.has ? fileTimestamps.get(watchfile) : fileTimestamps[watchfile]
this.prevTimestamps[watchfile] = nextTimestamp
return (prevTimestamp || this.startTime) < (nextTimestamp || Infinity)
})
// diff may be zero on initial build, thus also rebuild if there are no changes
return changedFiles.length === 0 || this.containsOwnDependency(changedFiles)
}
/**
* @param {Array} list - list of changed files as absolute paths
* @return {Boolean} true, if a file is a dependency of this i18n Plugin build
*/
containsOwnDependency(list) {
for (let i = 0; i < list.length; i += 1) {
if (this.fileDependencies.includes(list[i])) {
return true
}
}
return false
}
/**
* compile entry files
* @param {string} outputPath -
*/
compileAllEntryFiles(outputPath, done) {
glob(this.entry.length === 1 ? `${this.entry.join(',')}{/**/*,}` : `{${this.entry.join(',')}}{/**/*,}`, (err, entryFilesArray) => {
if (err) {
throw err
}
if (entryFilesArray.length === 0) {
log.warn(`no valid entry files found for ${this.entry} -- aborting`)
return
}
entryFilesArray.forEach((filepath) => this.compileEntryFile(filepath))
this.distI18nFile(outputPath)
// enforce new line after plugin has finished
done()
})
}
/**
* wirte **.i18n.json and manifest.json to output directory
* @param {string} outputDir -
*/
distI18nFile(outputPath) {
var manifestJson = {}
fs.emptyDirSync(this.outputDir)
if (this.isDev) {
this.checkMissingKey()
}
this.localsPrefix.forEach(key => {
var contentString = JSON.stringify(this.translates[key])
var baseName = this.isDev ? '.dev.json' : `.${this.hasherContentString(contentString)}.json`
manifestJson[key] = `${this.manifestBase}/${key}${baseName}`
var targetFilepath = `${this.outputDir}/${key}${baseName}`
this.distFileFun(targetFilepath, outputPath, contentString)
})
var manifestFilePath = `${this.outputDir}/manifest.json`
this.distFileFun(manifestFilePath, outputPath, JSON.stringify(manifestJson))
this.translates = Object.assign({}, this.translates)
}
distFileFun(targetFilepath, outputPath, result) {
//test
if (targetFilepath.includes(outputPath)) {
// change the destination path relative to webpacks output folder and emit it via webpack
targetFilepath = targetFilepath.replace(outputPath, "").replace(/^\/*/, "");
this.assetsToEmit[targetFilepath] = {
source: () => result,
size: () => result.length
};
} else {
// @legacy: if the filepath lies outside the actual webpack destination folder, simply write that file.
// There is no wds-support here, because of watched assets being emitted again
fs.outputFileSync(targetFilepath, result, "utf-8");
}
}
duplicatKeyCheck(baseTrans, newTrans, filePath) {
var duplicationKeys = helper.intersection(Object.keys(baseTrans), Object.keys(newTrans))
if (duplicationKeys.length) {
log.warn(`${filePath} has translation key duplicates: ${duplicationKeys.join(', ')} `)
}
}
checkMissingKey() {
var missingKey = helper.difference(Object.keys(this.translates['en']), Object.keys(this.translates['zh_cn']))
if (missingKey.length) {
log.warn(`has translation key missing: ${missingKey.join(', ')} `)
}
}
hasherContentString(contentString) {
const hasher = crypto.createHash('md5')
hasher.update(contentString)
// 6 digits should be enough
return hasher.digest('hex').substr(0, 6)
}
compileEntryFile(entryFile) {
try {
this.fileDependencies.push(entryFile)
var content = JSON.parse(fs.readFileSync(entryFile, 'utf-8'))
this.localsPrefix.forEach(local => {
if (path.basename(entryFile).indexOf(local) !== -1) {
if (this.isDev) {
this.duplicatKeyCheck(this.translates[local], content, entryFile)
}
Object.assign(this.translates[local], content)
}
})
} catch (e) {
log.error(`invalid json file ${entryFile}`)
}
}
registerGeneratedFile(filepath, content) {
this.assetsToEmit[path.basename(filepath)] = {
source: () => content,
size: () => content.length
};
}
/**
* Resets list of generated files
*/
clearGeneratedFiles() {
this.assetsToEmit = {};
}
/**
* Notifies webpack-dev-server of generated files
* @param {Compilation} compilation
*/
emitGeneratedFiles(compilation) {
Object.keys(this.assetsToEmit).forEach((filename) => {
compilation.assets[filename] = this.assetsToEmit[filename];
});
}
}
module.exports = RubickI18nWebpackPlugin