首页 > 解决方案 > 将 .json 文件从 html-webpack-plugin 传递到车把模板

问题描述

是否可以通过 html-webpack-plugin 加载 .json 文件并将其传递给我的车把文件?

我目前的设置

const path = require('path');
const fs = require('fs');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const webpack = require('webpack');

const extractCss = new ExtractTextPlugin({
  filename: './css/app.css'
});

const pages =  fs
    .readdirSync(path.resolve(__dirname, 'src/hbs/pages'))
    .filter(fileName => fileName.endsWith('.hbs'));

module.exports  = {
        context: path.resolve(__dirname, "src"),
        entry: './js/main.js',
        output: {
            path: path.resolve(__dirname, './build'),
            filename: 'js/app.js',
        },
        ...
        ...
        plugins: [
            new CleanWebpackPlugin(['build']),
            extractCss,
            ...pages.map(page => new HtmlWebpackPlugin({
                 template: 'hbs/pages/'+page,
                 filename: page
            }))
        ],

        module: {
            rules: [
                //babel-loader
                {
                    test: /\.js$/,
                    include: /src/,
                    exclude: /node_modules/,
                    use: {
                        loader: "babel-loader",
                        options: {
                            presets: ['env']
                        }
                    }
                },
                ...
                ...
                //handlebars-loader
                {
                    test: /\.(hbs)$/,
                    loader: "handlebars-loader",
                    query: {
                        helperDirs: [
                            __dirname + "/hbs/helpers"
                        ]
                    }
                }
            ]
        }
};

我想要一个包含 list1.json、list2.json 之类的文件的文件夹......这将非常巨大,这样我就不会弄乱我的 .hbs 文件。

就像是

...pages.map(page => new HtmlWebpackPlugin({
    template: 'hbs/pages/'+page,
    filename: page,
    data: myData.json
}))

会很好

干杯,格雷戈尔;)

标签: webpackhandlebars.jshtml-webpack-plugin

解决方案


你可以使用 html-webpack-plugin 的 templateParameters 选项:

new HtmlWebpackPlugin({
  templateParameters:require('path/to/data.json')
}),

templateParameters:允许覆盖模板中使用的参数


推荐阅读