Reputation: 385
I'm trying to import static html components in my templates,
I've this structure:
/src/home.html.ejs
/src/parts/header.html
/src/parts/breadcrumbs.html
/src/home.html.ejs body
<%= require('./header.html') %>
/src/parts/header.html
<h1>Title</h1>
<%= require('./breadcrumbs.html') %>
/src/parts/breadcrumbs.html
It's a breadcrumb!
When webpack is building I'm getting this in index.html:
<h1>Title</h1>
<%= require('./breadcrumbs.html') %>
Webpack config:
const path = require('path');
const miniCss = require('mini-css-extract-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
entry: './src/index.js',
output: {
publicPath: '',
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [
{
test: /\.html$/,
loader: 'html-loader',
},
{
test: /\.(s*)css$/,
use: [
miniCss.loader,
'css-loader',
'sass-loader',
]
},
{
test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'fonts/'
}
}
],
}
]
},
plugins: [
new miniCss({
filename: 'style.css',
}),
new HtmlWebpackPlugin({
title: 'Home',
template: path.resolve(__dirname, './src/home.html.ejs'),
filename: 'index.html',
})
],
devServer: {
contentBase: path.join(__dirname, 'dist'),
compress: true,
port: 9000
}
};
Also I found a couple of solutions when devs can use option interpolate in html-loader, but I'm using html-loader higher then v0.5.5 and this option was removed
What I'm doing incorrectly?
Upvotes: 0
Views: 1025
Reputation: 385
I figured it out by using ejs-webpack-loader:
npm i ejs-webpack-loader
webpack.config.js
const path = require('path');
const miniCss = require('mini-css-extract-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
entry: './src/index.js',
output: {
publicPath: '',
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [
{
test: /\.ejs$/,
use: [
{
loader: "ejs-webpack-loader",
}
]
},
{
test: /\.(s*)css$/,
use: [
miniCss.loader,
'css-loader',
'sass-loader',
]
},
{
test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'fonts/'
}
}
],
}
]
},
plugins: [
new miniCss({
filename: 'style.css',
}),
new HtmlWebpackPlugin({
title: 'Home',
template: path.resolve(__dirname, './src/home.html'),
filename: 'index.html',
})
],
devServer: {
contentBase: path.join(__dirname, 'dist'),
compress: true,
port: 9000
}
};
Structure
/src/home.html
/src/parts/header.ejs
/src/parts/breadcrumbs.ejs
in home.html
<%= require('./parts/header.ejs')() %>
in header.ejs
<%- require('./breadcrumbs.ejs')() %>
import child components with <%- not <%= and use brackets () in the end of import. You can pass some variables inside this brackets
in breadcrumbs.ejs
It's a breadcrumb!
Upvotes: 1