Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the same template file with HtmlWebpackPlugin and EJS?

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?

like image 914
Leo Jiang Avatar asked Jul 31 '19 04:07

Leo Jiang


People also ask

Do you deploy with Webpack or HTML?

Whilst most people use Webpack primarily for their JS scripts, there's always one final part of deploying that is forgotten: the HTML.

How do I include an EJS file in an HTML file?

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.

Should I use the same HTML template for production and development?

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.

What is EJS template engine in express?

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.


1 Answers

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})();
    }}`;
};
like image 112
Leo Jiang Avatar answered Sep 21 '22 14:09

Leo Jiang