In HtmlWebpackPlugin, <%-
means output escaped and <%=
means output unescaped. In EJS, it's the opposite. Is it possible to swap them for either HtmlWebpackPlugin or EJS?
Whilst most people use Webpack primarily for their JS scripts, there's always one final part of deploying that is forgotten: the HTML.
For example if you have "./views/users.ejs" and "./views/user/show.ejs" you would use <%- include ('user/show'); %>. You'll likely want to use the raw output tag ( <%-) with your include to avoid double-escaping the HTML output. EJS ships with a full-featured command-line interface.
The generated HTML file looks like so: As you can see, the CSS and the JS were placed into the file. Rather than have a template that's used for my production HTML and a static file I use in development, I'd rather have the same template used for both, to stop my HTML getting out of sync between environments.
Template engine is a part of Express that enables us to use static files in our applications.Template engine converts variables to values and changes the template to HTML files to send to the client. The default template engine of Express is Jade, but EJS is the most commonly used engine. In this article we will be discussing EJS only.
Here's the custom loader I used:
// From html-webpack-loader/lib/loader.js
const _ = require('lodash');
module.exports = function (source) {
const allLoadersButThisOne = this.loaders.filter(loader => loader.normal !== module.exports);
// This loader shouldn't kick in if there is any other loader (unless it's explicitly enforced)
if (allLoadersButThisOne.length > 0) {
return source;
}
// Skip .js files (unless it's explicitly enforced)
if (/\.js$/.test(this.resourcePath)) {
return source;
}
// The following part renders the template with lodash as a minimalistic loader
//
const template = _.template(source, {
interpolate: /<%-([\s\S]+?)%>/g,
escape: /<%=([\s\S]+?)%>/g,
variable: 'data',
});
// Use __non_webpack_require__ to enforce using the native nodejs require
// during template execution
return `var _ = __non_webpack_require__(${JSON.stringify(require.resolve('lodash'))});
module.exports = function (templateParams) { with(templateParams) {
return (${template.source})();
}}`;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With