如何使用webpack从pug模板输出html文件?

时间:2017-06-28 02:11:36

标签: webpack pug webpack-html-loader

我试图从我的webpack项目中的pug模板输出单个html文件。我遇到的问题是让pug-loader将html呈现到文件中。

我的webpack.config:

const path = require('path');
const glob = require('glob');
const webpack = require('webpack');

const src = path.resolve(__dirname, 'src');
const dist = path.resolve(__dirname, 'dist');

module.exports = {
  context: src,

  entry: {
    pug: glob.sync('./**/*.pug', {
      cwd: src
    }),
    index: path.resolve(src, 'index.js')
  },

  output: {
    path: dist,
    filename: '[name].js'
  },

  module: {
    rules: [
      {
        test: /\.js$/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['es2015'].map(dep =>
              require.resolve(`babel-preset-${dep}`)
            ) // Fix for lerna symlinked deps
          }
        }
      },
      {
        test: /\.pug$/,
        use: [
          {
            loader: 'file-loader',
            options: {
              name: '[path][name].html'
            }
          },
          'extract-loader',
          'html-loader',
          'apply-loader',
          'pug-loader'
        ]
      }
    ]
  }
};

这为我项目中的每个pug模板正确生成文件,但文件不包含html。相反,每个文件看起来像:

var req = require("!!<absolute-path-to-project>/node_modules/pug-loader/index.js!<absolute-path-to-pug-file>/index.pug");
module.exports = (req['default'] || req).apply(req, [])

我安装的依赖版本:

{
  "apply-loader": "^2.0.0",
  "babel-core": "^6.25.0",
  "babel-loader": "^7.1.0",
  "babel-preset-es2015": "^6.24.1",
  "extract-loader": "^0.1.0",
  "file-loader": "^0.11.1",
  "glob": "^7.1.2",
  "html-loader": "^0.4.5",
  "pug-loader": "^2.3.0",
  "webpack": "^3.0.0"
}

2 个答案:

答案 0 :(得分:9)

尝试使用pug-html-loader而不是pug-loader。

这是一个例子:

{
    test: /\.pug$/,
    use: [
      "file-loader?name=[path][name].html",
      "extract-loader",
      "html-loader",
      "pug-html-loader"
    ]
  }

答案 1 :(得分:-1)

这个问题很老,但你需要删除工作规则的“'html-loader'”