首页 > 解决方案 > 如何在 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?

我的文件结构如下所示:

索引.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"
      ]
    }]
  }
});

这是我的第一篇文章,如果我没有包含任何重要的内容,请告诉我!

谢谢!

标签: node.jsexpresswebpackejs

解决方案


推荐阅读