将 Pug 与 Visual Studio 2015 和 Webpack 一起使用

Using Pug with Visual Studio 2015 and Webpack

我对使用 Visual Studio 比较陌生,但我正在处理的项目是一个在 .cshtml 文件中包含多个页面的网站。我已经将 Webpack 设置为前端构建工具,并想开始使用 Pug as the templating engine. It makes more sense to me to have the build tool compile the Pug templates into HTML and keep my dependencies low, rather than Visual Studio compiling them (using something like PugViewEngine).

我是否应该创建一个 /pug 文件夹并开始将视图重新构建为 .pug 文件,并将任何 Razor 语法作为纯文本 - 然后使用 Webpack 编译为 HTML使用 .cshtml 文件扩展名并将其转储到 Visual Studio 项目的 /Views 文件夹中 - 或者是否有更好的方法来解决这个问题?

我设法利用 html-webpack-plugin, pug-loader and copy-webpack-plugin.

实现了这个功能

1) 确保在 webpack.config.js:

顶部需要 2 个插件
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');

2) 然后让 html-webpack-plugin 在您的 /src 文件夹中引用您的 index.pug 模板:

plugins: [
  new HtmlWebpackPlugin({
    template: './src/index.pug',
  })
]

3) 然后让 pug-loader 模块处理您的 .pug 文件:

module:  {
 rules: [
   {
    test: /\.pug$/,
    use: 'pug-loader'
   }
 ]
}

4) 然后使用 copy-webpack-plugin 将已编译的 HTML 文件从您的 /dist 文件夹移动到 Visual Studio 将要引用的 /Views/ 文件夹.将文件名更改为您喜欢的任何名称,并将文件扩展名更改为 .cshtml:

plugins: [
 new CopyWebpackPlugin([
  {
   from: 'dist/index.html',
   to: '../../Views/Shared/_layout.cshtml'
  }
 ])
]

5) .pug 模板中的任何剃须刀语法,您都可以将其视为带有 | 符号的纯文本:

| @Html.AntiForgeryToken();

可能有更简洁的方法来完成它,但一旦设置它就非常简单并且现在适用于我的项目,因为我们过渡到更简洁的前端流程。