handlebars-webpack-plugin
handlebars-webpack-plugin copied to clipboard
How to add bundled css and js to generated "pages"
Hello, I am able to generate html pages using partials but I would like the bundle.css and bundle.js added to the pages but can't see any examples of doing that.
My simplified webpack config (based on https://github.com/wbkd/webpack-starter)
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HandlebarsPlugin = require('handlebars-webpack-plugin');
module.exports = {
entry: {
app: path.resolve(__dirname, '../src/scripts/index.js'),
},
output: {
path: path.join(__dirname, '../build'),
filename: 'js/[name].js',
},
optimization: {
splitChunks: {
chunks: 'all',
name: false,
},
},
plugins: [
new HtmlWebpackPlugin({
template: path.resolve(__dirname, '../src/index.html'),
}),
new HandlebarsPlugin({
entry: path.join(process.cwd(), 'src', 'pages', '*.hbs'),
output: path.join(process.cwd(), 'build', '[name].html'),
data: path.join(process.cwd(), 'src/data.json'),
partials: ['src/components/*.hbs'],
}),
],
resolve: {
alias: {
'~': path.resolve(__dirname, '../src'),
},
},
module: {
rules: [
{
test: /\.mjs$/,
include: /node_modules/,
type: 'javascript/auto',
}
],
},
};
Files
- src/components/*.hbs (e.g. header, footer, nav, card, etc)
- src/pages/*.hbs (home, video, etc)
- src/data.json
Any update with getting this working? I'm having similar issues with no bundled CSS/JS appearing when using this plugin alongside html-webpack-plugin
Hi.
There are multiple options, none of them involves the handlebars-plugin, since its job is to compile handlebars-templates only. I am no longer working with this plugin, so i can only give you some directions right now.
- When you know your bundles filename, you can simply add the file with a
<script src>
-tag to your index.hbx file - If your bunde-file is hashed, you could try using the stats-replace-webpack-plugin to insert it on build time
- In case your bundle-filename is dynamically set in webpack.config you could also add the name into the json-file passed to handlebars and render the source into the script-tag
- Being webpack, there might be multiple other options, depending on config
Looking at your config, it seems the quickest option is to <script src="app.js"></script>
to your templates.
I hope this helps you getting started. Cheers.