将.json文件从html-webpack-plugin传递给handlebars模板

时间:2018-06-01 08:33:34

标签: webpack handlebars.js html-webpack-plugin

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

我当前的设置

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
}))

会很棒

欢呼声, 格雷戈尔;)

1 个答案:

答案 0 :(得分:2)

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

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

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