You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Webpack中将Handlebars模板编译为独立可分发HTML文件?

Hey there! Let's tackle this problem step by step—you're already halfway there with your Webpack setup, we just need to tweak a few things to get those multiple HTML files generated properly while keeping Handlebars template reusability intact.

1. Generate Multiple HTML Files with HtmlWebpackPlugin

The core issue right now is that you’re only using one instance of HtmlWebpackPlugin, which is why only one HTML file gets generated. To create separate files for each page (like index.html, contact.html), you just need to add multiple instances of the plugin—one for each root .hbs file.

Here’s how to update your plugins array:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'main.js',
    path: path.resolve(__dirname, 'dist'),
    clean: true, // Optional: Cleans the dist folder before each build
  },
  devServer: {
    static: path.join(__dirname, 'dist'),
    compress: true,
    port: 9000,
    open: true // Optional: Opens the browser automatically
  },
  module: {
    rules: [
      {
        test: /\.hbs$/,
        loader: "handlebars-loader"
      },
      // We'll add Sass support next
    ]
  },
  plugins: [
    // Generate index.html from index.hbs
    new HtmlWebpackPlugin({
      template: './src/index.hbs',
      filename: 'index.html'
    }),
    // Generate contact.html from contact.hbs
    new HtmlWebpackPlugin({
      template: './src/contact.hbs',
      filename: 'contact.html'
    })
    // Add more instances here for other pages like about.hbs, etc.
  ]
};

2. Enable Handlebars Template Reuse (Partials)

To keep using Handlebars partials (for headers, footers, etc.), you need to configure handlebars-loader to recognize your partial files. Let’s assume you store partials in a src/partials folder (e.g., src/partials/header.hbs, src/partials/footer.hbs).

Update your handlebars-loader rule to include partial directories:

{
  test: /\.hbs$/,
  loader: "handlebars-loader",
  options: {
    partialDirs: [path.resolve(__dirname, 'src/partials')],
    extensions: ['.hbs']
  }
}

Now you can reference partials in your root .hbs files like this:

{{> header}}
<main>
  <!-- Page content here -->
</main>
{{> footer}}

3. Automate Plugin Creation (For Multiple Pages)

If you have a lot of root .hbs files, manually adding a HtmlWebpackPlugin instance for each is tedious. Use the glob package to automatically generate plugin instances for all root .hbs files.

First, install glob:

npm install glob --save-dev

Then update your webpack config:

const glob = require('glob');

// ...

plugins: glob.sync('./src/*.hbs').map(filePath => {
  // Get the filename without extension (e.g., "index" from "src/index.hbs")
  const fileName = path.basename(filePath, '.hbs') + '.html';
  return new HtmlWebpackPlugin({
    template: filePath,
    filename: fileName
  });
})

This will automatically create an HTML file for every .hbs file in your src root.

4. Add Sass Support

You mentioned using Sass, so let’s add the necessary loaders to process .scss/.sass files. Install the required packages first:

npm install sass-loader sass css-loader style-loader --save-dev

Then add this rule to your module.rules:

{
  test: /\.s[ac]ss$/i,
  use: [
    // Injects CSS into the DOM (use MiniCssExtractPlugin for production builds)
    'style-loader',
    // Translates CSS into CommonJS
    'css-loader',
    // Compiles Sass to CSS
    'sass-loader',
  ],
}

For production, replace style-loader with MiniCssExtractPlugin to extract CSS into separate files (instead of embedding it in JS):

npm install mini-css-extract-plugin --save-dev

Then update the rule and add the plugin:

const MiniCssExtractPlugin = require('mini-css-extract-plugin');

// ...

module.rules: [
  // ... other rules
  {
    test: /\.s[ac]ss$/i,
    use: [
      MiniCssExtractPlugin.loader,
      'css-loader',
      'sass-loader',
    ],
  },
]

plugins: [
  // ... other plugins
  new MiniCssExtractPlugin({
    filename: '[name].css'
  })
]

5. Verify URL Structure

Once you build the project, your dist folder will have index.html, contact.html, etc. In Webpack Dev Server, you can access them directly via URLs like http://localhost:9000/contact.html—no extra config needed here, since dev server serves files from the dist directory.


内容的提问来源于stack exchange,提问作者CaptainCarl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 18:37:50