Skip to content

Instantly share code, notes, and snippets.

@alunny
Last active December 12, 2016 23:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alunny/e4be66a922d036fe89243ad3e7c6da93 to your computer and use it in GitHub Desktop.
Save alunny/e4be66a922d036fe89243ad3e7c6da93 to your computer and use it in GitHub Desktop.
webpack plugin question
var _ = require('i18n_library');
modules.exports = {
literalPhrase: "Hola Sean",
parameterizedPhrase: _("Hola {{person}}", { person: "Sean" })
}
var _ = require('i18n_library');
modules.exports = {
literalPhrase: _("Hello world"),
parameterizedPhrase: _("Hello {{person}}", { person: "Sean" })
}
var _ = require('i18n_library');
modules.exports = {
literalPhrase: _("Hola Sean"),
parameterizedPhrase: _("Hola {{person}}", { person: "Sean" })
}
// based on https://github.com/webpack/i18n-webpack-plugin
// but tweaked for Twitter specific quirks (different second param in particular)
var BasicEvaluatedExpression = require('webpack/lib/BasicEvaluatedExpression');
var ConstDependency = require('webpack/lib/dependencies/ConstDependency');
function TwitterI18NPlugin(phrases, options) {
if (typeof phrases !== 'object') {
throw new Error('TwitterI18NPlugin: missing phrases object');
}
this.options = options || {};
this.phrases = phrases;
}
TwitterI18NPlugin.prototype.apply = function(compiler) {
var phrases = this.phrases;
compiler.plugin('compilation', function(compilation, params) {
compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
});
// calls to the underscore (translate) function
// this never gets called when underscore is bound to a variable in the module
compiler.parser.plugin('call _', function(expr) {
var param = this.evaluateExpression(expr.arguments[0]);
if (!param.isString) {
return;
}
var str = param.string;
var translation = phrases[str];
if (translation) {
// replace full function call, or just the first arg if there are multiple
var source = expr.arguments.length > 1 ? expr.arguments[0] : expr;
var dep = new ConstDependency(JSON.stringify(translation), source.range);
dep.loc = source.loc;
this.state.current.addDependency(dep);
return true;
}
});
};
module.exports = TwitterI18NPlugin;

The call _ parser plugin hook doesn't get executed because it's already been transformed into a BasicEvaluatedExpression, so this conditional is false: https://github.com/webpack/webpack/blob/v1.13.1/lib/Parser.js#L726

I can hook into the program part of the parse (ie. compiler.parser.plugin('program')) but then I have to traverse the ast myself (which is doable but I'd prefer to use the call _ hook).

Question: is there a better way than using compiler.parser.plugin('program', function(ast) { .. }) here?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment