twig-html-loader

raw JSON →
0.1.9 verified Sat Apr 25 auth: no javascript maintenance

Webpack loader that compiles Twig templates into an HTML string using Twig.js. Version 0.1.9 is the latest stable release (last updated 2019). It integrates with webpack to process .twig files, supports data injection, caching, namespaces, and custom Twig extensions (functions, filters, tests, tags). Compared to alternatives like twig-loader, it returns raw HTML string rather than a compiled template function, which simplifies usage with html-webpack-plugin. Requires raw-loader as a peer dependency. Low maintenance cadence (no updates since 2019).

error Module build failed: Error: You may need an additional loader to handle the result of these loaders.
cause Missing raw-loader before twig-html-loader.
fix
Add 'raw-loader' to the use array before 'twig-html-loader'.
error Cannot find module 'twig'
cause twig-html-loader depends on twig (Twig.js) but it may not be installed.
fix
Install twig as a dependency: npm install twig --save-dev
breaking Requires raw-loader to be chained before twig-html-loader. Without it, the loader receives a module object instead of raw Twig content.
fix Add 'raw-loader' before 'twig-html-loader' in the use array.
gotcha Data option function must call context.addDependency() to enable webpack watch; using require() caches the file and breaks HMR.
fix Use context.addDependency() as shown in the README watch-data example.
gotcha When using with html-webpack-plugin, both entries in use array (raw-loader and twig-html-loader) must be provided; omitting raw-loader causes a compilation error.
fix Always include raw-loader before twig-html-loader.
npm install twig-html-loader
yarn add twig-html-loader
pnpm add twig-html-loader

webpack config to compile Twig templates to HTML strings using raw-loader and twig-html-loader.

// webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: './src/index.js',
  output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.js' },
  module: {
    rules: [
      {
        test: /\.twig$/,
        use: ['raw-loader', 'twig-html-loader']
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/index.twig'
    })
  ]
};