ejs-loader

raw JSON →
0.5.0 verified Sat Apr 25 auth: no javascript

Webpack loader that compiles EJS templates using lodash/underscore's _.template function. Current stable version is 0.5.0, with maintenance releases every few years. Key differentiator from ejs-compiled-loader: it uses lodash/underscore template syntax, not the EJS templating engine. Requires ProvidePlugin for global '_'. Supports custom delimiters via options, and ES module export by default with an option to switch to CommonJS. The 'variable' option is required to avoid strict mode errors with ES modules.

error Module not found: Error: Cannot resolve module 'ejs-loader'
cause ejs-loader is not installed.
fix
Run 'npm install ejs-loader --save-dev'.
error Error: ejs-loader: You must provide a 'variable' option when using ES modules.
cause Missing 'variable' option in loader configuration with esModule: true (default).
fix
Add options: { variable: 'data' } to the loader rule.
error Uncaught ReferenceError: _ is not defined
cause Lodash/underscore is not provided globally at runtime.
fix
Add new webpack.ProvidePlugin({ _: 'lodash' }) to webpack plugins.
error Uncaught TypeError: template is not a function
cause The required module is not being used as a function; it's the compiled template function.
fix
Call the required module: const html = require('./template.ejs')({ data });
gotcha The 'variable' option is required for the loader to work with ES module exports; otherwise strict mode errors occur.
fix Add 'variable: 'data'' to loader options in webpack config.
deprecated Using 'module.loaders' array and 'loader' string is deprecated in webpack 4+.
fix Use 'module.rules' array with 'use' array and 'loader' string inside object.
gotcha The loader returns a template function, not the rendered HTML string; you must call it with data.
fix Call the required module as a function: const html = template(data);
gotcha Requires a global '_' variable (lodash/underscore) at runtime; use ProvidePlugin.
fix Add new webpack.ProvidePlugin({ _: 'lodash' }) to plugins in webpack config.
npm install ejs-loader
yarn add ejs-loader
pnpm add ejs-loader

Shows a minimal webpack 4+ config with ejs-loader, ProvidePlugin for lodash, and usage of the compiled template function.

// webpack.config.js
const webpack = require('webpack');
module.exports = {
  entry: './src/index.js',
  module: {
    rules: [
      {
        test: /\.ejs$/,
        use: [
          {
            loader: 'ejs-loader',
            options: { variable: 'data' }
          }
        ]
      }
    ]
  },
  plugins: [
    new webpack.ProvidePlugin({ _: 'lodash' })
  ]
};

// src/index.js
const template = require('./template.ejs');
const html = template({ name: 'World' });
document.body.innerHTML = html;

// src/template.ejs
<h1>Hello <%= data.name %>!</h1>