使用Webpack和Moustache渲染与主应用程序无关的多个页面

时间:2019-04-08 10:46:58

标签: javascript webpack mustache

我正在开发Chrome扩展程序,并使用Webpack对其进行捆绑。我有编译后的捆绑包,这是应用程序的主要部分,但是我还需要一个选项页面来描述功能。此选项页面与捆绑软件无关,只是一个静态HTML文件。

我必须在该选项页面中放很多东西,所以我想使用Mustache渲染该页面并使用JavaScript定义所有内容。在大多数情况下,我已经做到了。

这是我的Webpack配置(我已经删除了与我的应用有关的部分):

const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
  output: {
    path: path.join(__dirname, 'extension/build/')
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/options/index.html',
      inject: false
    })
  ],
  module: {
    rules: [
      {
        test: /\.html$/,
        loader: 'mustache-loader',
        options: {
          render: require('./src/options/index.js')
        }
      }
    ]
  }
}

在我的src/index.js中,我有:

require('./options/index.html')

这将打开模板并将其与src/options/index.js中的数据一起呈现。

但是,这是一个问题。我使用webpack --watch运行Webpack,并且对index.js(包含模板数据)的更改不会触发重建。另外,以相同的方式创建另一个静态HTML文件时,我将需要花费很多麻烦。

如果HtmlWebpackPlugin在入口点自动使用模板require(),这样就不需要显式设置它,那将是理想的。另外,如果它在同一位置自动使用js来获取数据,那就太好了。例如:

require('./options/index.html`)

使用来自./options/index.html.js的数据渲染模板,然后将其发出。如果将其发送到Webpack配置中指定的自定义文件夹,那就更好了。

有可能吗?我找不到能做到这一点的插件/加载器。


编辑:我可以通过将render选项指定为函数来部分解决重建问题:

{
  test: /\.html$/,
  loader: 'mustache-loader',
  options: {
    render () {
      var file = './src/options/index.js'
      delete require.cache[require.resolve(file)]
      return require(file)
    }
  }
}

但是它仍然不能正常工作。只有在对index.html进行更改之后,才会触发重建。这意味着,如果我更改index.js,则还需要保存index.html来触发构建。

0 个答案:

没有答案