使用Angular2和Webpack如何压缩HTML模板?

5

我正在使用这里的webpack入门:

https://github.com/AngularClass/angular2-webpack-starter

在 webpack 的配置中,有这样的代码(我自己添加了 minify 选项)。
new HtmlWebpackPlugin({ template: 'src/index.html', chunksSortMode: 'none',
      minify: {
        collapseWhitespace: true,
        collapseInlineTagWhitespace: true,
        // removeTagWhitespace: true,
        removeRedundantAttributes: true,
        removeEmptyAttributes: true,
        removeScriptTypeAttributes: true,
        removeStyleLinkTypeAttributes: true
      }  }),

它可以缩小index.html文件。但在项目中还有许多其他作为angular 2模板的html文件。如何对它们进行缩小处理?
我看到的其他html文件被编译成一个javascript文件-main.bundle.js。
我希望这是可能的,使用webpack。如果不行,也许有其他工具?
更新:
我检查了https://github.com/bestander/html-minify-loader,它使用https://github.com/Swaagie/minimize,并且这是它所写的:
Minimize不解析内联PHP或原始模板文件。模板不是有效的HTML,这超出了最小化的范围。应该解析和缩小模板的输出。
因此,对我来说将不起作用,因为它们是angular 2模板。

对于模板,您可以使用 html-minify-loader(https://github.com/bestander/html-minify-loader) - Bob Sponge
1个回答

9

如果您需要在生产环境中进行模板缩小,请在webpack.prod.config.js(第109行)添加以下代码:

loaders: ['raw-loader', 'html-minify-loader'],

安装 html-minify-loader 加载器:
npm install html-minify-loader --save-dev

并按照文档所述添加指定的缩小选项(参见文档)

 'html-minify-loader': {
     empty: true,        // KEEP empty attributes
     cdata: true,        // KEEP CDATA from scripts
     comments: true,     // KEEP comments
     dom: { // options of !(htmlparser2)[https://github.com/fb55/htmlparser2]
      lowerCaseAttributeNames: false, // do not call .toLowerCase for each attribute name (Angular2 use camelCase attributes)
     }
  }

谢谢,你太棒了。我以为这不会起作用,但是既然你写了,我就试了一下,结果确实可以。我不确定为什么,即使没有压缩选项,它也会从HTML中删除空格。 - Dariux
使用默认选项删除空格:https://github.com/Swaagie/minimize - Bob Sponge

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接