twigjs-loader

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

Webpack loader for compiling Twig.js templates. Current stable version is 1.0.3, released with support for Node.js >=8. It integrates Twig templates into webpack builds, allowing template imports in JavaScript and TypeScript. Key differentiators: provides an Express view engine helper, supports Hot Module Replacement, and offers a customizable renderTemplate option for advanced compilation control. Ships TypeScript type definitions. Peer dependency on twig 1.x.

error Module not found: Error: Can't resolve 'twig' in '...'
cause Missing peer dependency 'twig'.
fix
npm install twig@1
error Error: Template not found: ... .twig
cause Webpack cannot resolve the template path relative to the importing file.
fix
Use absolute paths or configure webpack resolve.modules/resolve.alias.
error TypeError: Cannot read property 'render' of undefined
cause The twig object is not initialized correctly in custom renderTemplate.
fix
Ensure 'require("twig").twig' returns a function and that twigData is valid.
gotcha Requires peer dependency 'twig' version 1.x - must be installed separately.
fix Run 'npm install twig@1' alongside twigjs-loader.
gotcha Template path resolution is delegated to webpack; custom namespaces require additional webpack resolve configuration.
fix Configure webpack resolve.alias or resolve.modules for custom template directories.
gotcha ExpressView helper requires twigjs-loader to be in the same project; not a separate export.
fix Import { ExpressView } from 'twigjs-loader' and set app.set('view', ExpressView).
npm install twigjs-loader
yarn add twigjs-loader
pnpm add twigjs-loader

Basic setup: webpack config with twigjs-loader, importing a Twig template in ESM, and rendering it with data.

// webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.twig$/,
        use: {
          loader: 'twigjs-loader',
          options: {
            renderTemplate(twigData, dependencies, isHot) {
              return `
                ${dependencies}
                var twig = require("twig").twig;
                var tpl = twig(${JSON.stringify(twigData)});
                module.exports = function(context) { return tpl.render(context); };
              `;
            },
          },
        },
      },
    ],
  },
};

// index.js
import indexView from './index.twig';
document.body.innerHTML = indexView({ name: 'World' });

// index.twig
<h1>Hello {{ name }}!</h1>