babel-plugin-nunjucks/index.js

24 lines
811 B
JavaScript
Raw Permalink Normal View History

2022-02-01 19:07:08 +03:00
import nunjucks from 'nunjucks';
2021-10-04 21:19:14 +03:00
2022-02-01 19:07:08 +03:00
export default ({types: t}) => {
return {
2022-12-15 13:35:15 +03:00
pre(state) {
const options = state.opts.plugins[0].options;
this.njkenv = new nunjucks.Environment(new nunjucks.FileSystemLoader(options.templatesFolder));
if (options.globals) {
options.globals.forEach(({name, value}) => {
this.njkenv.addGlobal(name, value);
});
}
},
2022-02-01 19:07:08 +03:00
visitor: {
2022-12-15 13:35:15 +03:00
TaggedTemplateExpression(path) {
if (path.get('tag').isIdentifier({name: 'njk'})) {
const render = this.njkenv.renderString(path.node.quasi.quasis[0].value.raw);
path.replaceWith(t.stringLiteral(render));
2022-02-01 19:07:08 +03:00
}
},
},
};
2021-10-04 21:19:14 +03:00
};