-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
68 lines (54 loc) · 2.02 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
'use strict';
const staticI18n = require('static-i18n');
const minimatch = require('minimatch');
const path = require('path');
const { RawSource } = require('webpack-sources');
class StaticI18nHtmlPlugin {
constructor(options) {
this.options = options;
// In webpack memory the baseDir is the root. Ensure static-i18n thinks that too!
this.options.baseDir = '';
this.options.outputDir = '';
}
apply(compiler) {
compiler.hooks.emit.tapAsync('WebpackStaticI18NPlugin', async (compilation, callback, stats) => {
let globPattern = this.options.files;
let assetsToTranslate = minimatch.match(Object.keys(compilation.assets), globPattern)
for (let i in assetsToTranslate ) {
let filename = assetsToTranslate[i];
// static-i18n needs this to determine the relative path for resources.
this.options.file = filename;
let translatedSources = await staticI18n.process( compilation.assets[filename].source(), this.options );
if ( this.options.suppressRaw ) {
delete compilation.assets[filename];
}
for (let locale in translatedSources) {
let filenameNew = this.getTranslatedFileName(filename, locale );
compilation.assets[filenameNew] = new RawSource(translatedSources[locale]);
}
}
callback();
});
}
getTranslatedFileName( file, locale ) {
let output = '';
if ( this.options.outputPrefix ) {
file = path.relative(this.options.outputPrefix, file);
}
if ( locale === this.options.locale ) {
output = this.options.outputDefault || '__file__'
}
else {
output = this.options.outputOther || '__lng__/__file__'
}
let outputFile = output
.replace('__lng__', locale)
.replace('__file__', file)
.replace('__basename__', path.basename(file, path.extname(file)));
if ( this.options.outputPrefix ) {
outputFile = path.join( this.options.outputPrefix + '/', outputFile );
}
return outputFile;
}
}
module.exports = StaticI18nHtmlPlugin;