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).
Common errors
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
Warnings
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.
Install
npm install twig-html-loader yarn add twig-html-loader pnpm add twig-html-loader Imports
- twig-html-loader wrong
{ test: /\.twig$/, use: 'twig-html-loader' }correct{ test: /\.twig$/, use: ['raw-loader', 'twig-html-loader'] } - HtmlWebpackPlugin wrong
import HtmlWebpackPlugin from 'html-webpack-plugin';correctconst HtmlWebpackPlugin = require('html-webpack-plugin'); - data option as function wrong
data: () => { return require('./data.json'); }correctdata: (context) => { context.addDependency('./data.json'); return { /* ... */ }; }
Quickstart
// 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'
})
]
};