-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
57 lines (53 loc) · 1.73 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
const ConstDependency = require('webpack/lib/dependencies/ConstDependency');
const {
toConstantDependency,
} = require('webpack/lib/javascript/JavascriptParserHelpers');
class MiniI18nWebpackPlugin {
constructor(translations) {
this.translations = translations;
this.name = 'MiniI18nWebpackPlugin';
}
createHandler(compilation) {
return (parser) => {
const { translations, name } = this;
parser.hooks.call.for('__').tap(name, (expr) => {
const keyExpr = parser.evaluateExpression(expr.arguments[0]);
if (!keyExpr.isString()) {
compilation.errors.push('Translation key must be a string');
return false;
}
const key = keyExpr.asString();
if (translations && !(key in translations)) {
compilation.warnings.push(`Missing translation: ${key}`);
}
const value = (translations || {})[key] || key;
return toConstantDependency(parser, JSON.stringify(value))(expr);
});
};
}
apply(compiler) {
const { name } = this;
compiler.hooks.compilation.tap(name, (compilation) => {
compilation.dependencyTemplates.set(
ConstDependency,
new ConstDependency.Template(),
);
});
compiler.hooks.compilation.tap(
name,
(compilation, { normalModuleFactory }) => {
const handler = this.createHandler(compilation);
normalModuleFactory.hooks.parser
.for('javascript/auto')
.tap(name, handler);
normalModuleFactory.hooks.parser
.for('javascript/dynamic')
.tap(name, handler);
normalModuleFactory.hooks.parser
.for('javascript/esm')
.tap(name, handler);
},
);
}
}
module.exports = MiniI18nWebpackPlugin;