Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass .json file from html-webpack-plugin to handlebars template

Is it possible to load a .json file via html-webpack-plugin and pass it to my handlebar files?

my current setup

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"
                        ]
                    }
                }
            ]
        }
};

I want to have a folder with files like list1.json, list2.json... which will be very huge, so that i dont mess up my .hbs file.

something like

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

would be great

cheers, gregor ;)

like image 660
Gregor Voinov Avatar asked Jan 29 '23 00:01

Gregor Voinov


1 Answers

you can use html-webpack-plugin's templateParameters option:

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

templateParameters: Allows to overwrite the parameters used in the template

like image 173
loveky Avatar answered Apr 30 '23 02:04

loveky