node.js - 如何在 webpack 中使用 ejs 模板/部分?
问题描述
我正在尝试使用 Express 和 ejs 创建一个完整的堆栈应用程序,并使用 webpack 捆绑客户端资产。当我在没有 ejs 的情况下设置它时,它一切正常。当我尝试将 index.html 更改为使用部分页眉、页脚等的 index.ejs 时,问题就出现了。最终这将是一个多页应用程序,这就是我使用 ejs 模板的原因。
我尝试过使用 ejs-loader ( https://www.npmjs.com/package/ejs-loader )、ejs-compiled-loader ( https://github.com/bazilio91/ejs-compiled-loader ) 和 ejs -html-loader ( https://www.npmjs.com/package/ejs-html-loader ) 毫无乐趣。
任何帮助,将不胜感激。我确信这真的很简单,但对于我的生活,我无法弄清楚如何将 ejs 链接到 webpack 并让模板工作。
我在下面包含了与 template.html 一起使用的代码。我需要知道如何更改它以使用 index.ejs?
我的文件结构如下所示:
- --dist(来自 webpack 的输出)
- --src(包含 index.ejs)
- ----partials(包含 index.ejs 的部分)
- 应用程序.js
- webpack.common.js
- webpack.dev.js
- webpack.prod.js
- package.json 等
索引.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<% include partials/head %>
</head>
<body>
<main>
<% include partials/main %>
</main>
<% include partials/footer %>
</body>
</html>
我的配置文件如下所示(我只包含了两个合并以进行构建配置):
webpack.common.js
const path = require("path")
module.exports = {
entry: {
main: "./src/index.js",
vendor: "./src/vendor.js"
},
module: {
rules: [
{
test: /\.html$/,
use: ["html-loader"]
},
{
test: /\.(svg|png|jpg|gif)$/,
use: {
loader: "file-loader",
options: {
name: "[name].[hash].[ext]",
outputPath: "imgs"
}
}
}
]
},
}
webpack.prod.js
const path = require("path")
const common = require("./webpack.common")
const merge = require("webpack-merge")
const {
CleanWebpackPlugin
} = require('clean-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const TerserPlugin = require("terser-webpack-plugin");
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = merge(common, {
mode: "production",
output: {
filename: "[name].[contentHash].js",
path: path.resolve(__dirname, "dist")
},
optimization: {
minimizer: [
new OptimizeCssAssetsPlugin(),
new TerserPlugin(),
new HtmlWebpackPlugin({
template: "./src/template.html",
minify: {
removeAttributeQuotes: true,
collapseWhitespace: true,
removeComments: true,
}
})]
},
plugins: [
new MiniCssExtractPlugin({
filename: "[name].[contentHash].css",
}),
new CleanWebpackPlugin(),
],
module: {
rules: [{
test: /\.scss$/,
use: [
MiniCssExtractPlugin.loader,
"css-loader",
"sass-loader"
]
}]
}
});
这是我的第一篇文章,如果我没有包含任何重要的内容,请告诉我!
谢谢!
解决方案
推荐阅读
- javascript - NextJs 空查询
- kubernetes - kubernetes (minikube) 中的 Fabric v2.0 - 错误 Peer channel join - 由于 pod 的名称而导致的 TLS 问题
- mysql - 如何根据表的值添加列
- linux - 奇怪的 CPU 使用率:100% 使用率,但温度异常低
- embedded-linux - buildroot中有多个分区?
- bpf - eBPF 数据包监视器在“ping -f”时丢失了一些数据包
- amazon-web-services - AWS Elastic Beanstalk:将容器日志流式传输到 CloudWatch 问题
- angular - Angular FormGroup 和 RxJs
- android - 如何在 Android 的 HID 游戏手柄中实现左右模拟触发器
- mongodb - 不使用 SSH 连接远程 MongoDB 服务器