【问题标题】:Include JS (& CSS) Tags in emitted HTML from Nunjucks Plugin (or Loader)在 Nunjucks 插件(或加载器)发出的 HTML 中包含 JS(和 CSS)标签
【发布时间】:2019-10-16 21:10:20
【问题描述】:

使用html-webpack-plugin时,插件可以注入JS标签(以及其他标签,如CSS等)。

当尝试使用 nunjucks-webpack-plugin (et al) 时,我希望获得同样的便利。

但是,当我使用 nunjucks-webpack-plugin(等)时,我似乎无法找到让 Webpack 注入脚本标签的方法。

诚然,我对使用 Webpack 很陌生,所以我可能缺少一些基本的东西。

我尝试了各种插件和加载器,以各种链顺序。

使用的加载器和插件: - nunjucks 装载机 - 超级修女装载机 - nunjucks-webpack-plugin

这是我想使用的链接类型的示例:

const path = require("path");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const NunjucksWebpackPlugin = require("nunjucks-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
  // ...
  entry: {
    index: "./src/index.js"
  },
  output: {
      path: path.resolve(__dirname, "dist"),
      filename: "[name].[hash].js"
  },
  // ...
  plugins: [
    new CleanWebpackPlugin(),
    new NunjucksWebpackPlugin({
      templates: [
        {
          from: "./src/index.njk",
          to: "_temp_.html"
        }
      ]
    }),
    new HtmlWebpackPlugin({
      template: "_temp_.html",
      filename: "index.html",
      chunks: ["index"]
    })
  ]
  // ...
};

结果将是编译后的 Nunjucks 模板的 HTML,在 Javascript 脚本标记 () 之前注入。

【问题讨论】:

  • 有一个与 html-webpack-plugin 兼容的simple-nunjucks-loader(我是作者)(参见文档中的示例)。

标签: webpack nunjucks


【解决方案1】:

nunjucks-webpack-plugin的文档中

webpack 编译变量也会通过__webpack__ 对象下的模板发送到:hash

我们可以使用类似的东西:

<script type="text/javascript" src="/assets/js/index.{{ __webpack__.hash }}.js"></script>

【讨论】:

    猜你喜欢
    • 2012-09-09
    • 1970-01-01
    • 2014-09-07
    • 1970-01-01
    • 1970-01-01
    • 2019-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多