繁体   English   中英

如何在 webpack 中加载 Pug 模板而不编译到 HTML?

[英]How to load Pug templates in webpack without compiling to HTML?

pug-loaderpug-html-loader似乎都专注于将 Pug 模板预编译为 HTML。 我不想这样做,因为我需要一些只有在渲染模板时才能获得的动态渲染功能,比如能够传入页面的标题,作为一个简单的例子。

然而,我想做的是使用 Webpack 来处理 Pug 模板,以便通过它们 go,找出它们使用的图像,然后将这些图像加载到/dist文件夹。 我还希望能够在可能的情况下使用url-loader将数据 URL 内联到 Pug 模板中,这意味着它们需要在此过程中被复制和修改。

试试这个:

{
      test: /.pug$/,
      use : [
        {
          loader : ['html-loader', 'pug-html-loader'],
          options : {
            attrs : ['img:src']
          }
        }
      ]
    }

我知道这个问题有多老了,但我努力尝试解决这个问题,我终于找到了一个使用扩展 html-webpack-plugin 的 html-webpack-pug-plugin 的解决方案

const HtmlWebpackPlugin = require('html-webpack-plugin')
const HtmlWebpackPugPlugin = require('html-webpack-pug-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')

module.exports = {
  entry: {
    home: "./src/index.js",
  },
  output: {
     path: path.resolve(__dirname, "./public"),
     filename: "[name].js",
     publicPath: "/public",
     clean: true,
  },
  module: {
    rules: [
       {
        test: /\.(css|sass|scss)$/,
        use: [MiniCssExtractPlugin.loader, "css-loader"],
      },
    ],
  },
  plugins: [
    new MiniCssExtractPlugin(),
    new HtmlWebpackPlugin({
      template: "./views/_head.pug",
      filename: "../views/head.pug",
      minify: false,
      inject: "head",
    }),
    new HtmlWebpackPugPlugin(),
  ],
};

您应该只调用一次 HtmlWebpackPugPlugin,如文档https://github.com/negibouze/html-webpack-pug-plugin#usage中所述

对于要注入的代码,模板 _head.pug 需要有一个 body 标签以便代码被注入 要正确缩进代码,它还需要有一个 html 标签

_head.pug

doctype html
html
  head

  body

构建后:head.pug

doctype html
html
  head
    script(defer src="/public/home.js")
    link(href="/public/home.css" rel="stylesheet")

  body

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM