How can I set up Webpack 4.5 to inject an html file, that has their own css file, into a main index.html without frameworks like Angular, React, etc. and without having a javaScript file for each html file I want to inject?
I've already created separate html files and inject them into index.html, but haven't figured out how to make those html templates have their own local-scoped css files.
Inside home.html I want to be able to use classes from home.css, like normal
(i.e. not like <div className={styles.foo}>
, which is the closest I've found)
home.html
<div class=foo></div>
<div>
<p class=bar></p>
</div>
home.css (local scope)
.foo {background: red;}
.bar {background: green;}
and have it automatically locally-scoped so that in my index.html I can inject home.html without css conflicts and without having each .html file need it's own .js file.
index.html
<!doctype html>
<html lang="en">
<head>
<title>Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="styles.css" rel="stylesheet">
</head>
<body>
<div id="pages">
<!-- inject page templates below -->
<section id="home" class="page">${require("./pg-templates/home/home.html")}</section>
</div>
</body>
</html>
styles.css (global scope)
* {box-sizing: border-box;}
body
{
padding: 0;
margin: 0;
}
.foo /*this will be overridden by the .foo class in home.css*/
{
background: yellow;
color: purple;
}
webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
module.exports = {
entry: './src/main.js',
devServer: {
contentBase: './src',
port: 4200,
open: true
},
plugins: [
new HtmlWebpackPlugin({
hash: true,
template: './src/index.html'}),
new UglifyJsPlugin()
],
module: {
rules: [
{
test: /\.jsx?$/,
include: /src/,
exclude: /node_modules/
},
{
test: /\.(html)$/,
exclude: /node_modules/,
use: {
loader: 'html-loader',
options: {
attrs:[':data-src'],
minimize: true,
conservativeCollapse: false,
interpolate: true
}
}
},
{
test: /\.css$/,
use: [
{ loader: 'style-loader' },
{
loader: 'css-loader',
options: {
modules: true,
localIdentName: '[path][name]__[local]--[hash:base64:5]'
}
}
]
}
]
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
}
}