foreword
Due to project reasons, it is necessary to use the native three-piece set to minimize the writing of the product's homepage. I really can't stand the css and the whole html writing method. I found a solution by myself. I can use a set of codes to cover different language js, but it is not perfect yet. of.
If you don’t want to see my bb, here’s the project address first
Dependency installation
# babel + ts
yarn add @babel/core @babel/preset-env @babel/preset-typescript typescript -D
# webpack
yarn add webpack webpack-dev-server webpack-cli -D
# loader
yarn add babel-loader ejs-loader -D
# webpack-plugin
yarn add html-webpack-plugin -D
webpack configuration
Only part of the dev configuration is shown here, build it yourself to find it in the project, I am lazy
webpack.dev.js
const path = require('path')
const HTMLWebpackPlugin = require('html-webpack-plugin')
const webpack = require('webpack')
module.exports = {
entry: [
'webpack/hot/dev-server',
path.join(__dirname, './app.ejs'),
path.join(__dirname, './main.ts'),
],
target: 'web',
mode: 'development',
cache: {
type: 'memory',
},
devtool: 'cheap-module-source-map',
output: {
filename: 'app.js',
path: path.join(__dirname, './dist'),
publicPath: '/',
},
module: {
rules: [
{
test: /\.[tj]s?$/,
exclude: /node_modules/,
use: ['babel-loader'],
},
{
test: /\.ejs$/,
use: [
{
loader: 'ejs-loader',
options: {
esModule: false,
variable: 'data',
},
},
],
},
],
},
devServer: {
contentBase: path.join(__dirname, './dist'),
compress: true,
port: 9000,
hot: true,
},
resolve: {
extensions: ['.ts', '.js', '.json'],
},
context: path.resolve(__dirname),
plugins: [
new webpack.DefinePlugin({
'process.env.build_lang': `"${
process.env.build_lang}"`,
}),
new HTMLWebpackPlugin({
template: path.join(__dirname, './app.ejs'),
filename: 'index.html',
}),
new webpack.HotModuleReplacementPlugin(),
],
}
ejs-loader
The configuration items here variable
are very critical and will be associated with the referenced ejs module later
to develop
main.ts can be whatever you want, the focus is only on the introduction of the ejs module
app.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div class="layout-container <%= process.env.build_lang %>">
<%= require('./m1.ejs')({a1:'asd'}) %>
</div>
</body>
</html>
m1.ejs
<div class="m1">
<p>a:<%= data.a1 %></p>
</div>
The data passed in is passed m1.ejs
in as object type , which is the same as that data
configured by webpackvariable
data
epilogue
html-webpack-plugin itself supports ejs, so this job is done. Currently known bugs are
- The imported sub-ejs module does not trigger hot update
- The hot update of ejs is to refresh the entire page
This environment itself is designed to solve a set of codes that can be used in multiple languages + easy to maintain. If there is anything that can be improved, please suggest it.