如何为 Pug、React 和 ES6 设置 webpack

How to set up webpack for Pug, React, and ES6

我正在尝试使用 React 和 ES6 制作一个网站。我正在使用 Webpack 通过 Babel 转译我的 JS,它工作正常。现在我需要知道如何在 Pug(或 HTML 中编写我的模板)并将其添加到 Webpack 工作流中。我希望我的构建文件夹有两个文件:

  1. 我的bundle.js
  2. 我的 index.html 文件从我的 index.pug 文件编译而成

示例 webpack.config.js 文件会有所帮助,但我真正想要的只是如何执行此操作的一般思路。

谢谢!

要在 webpack 中使用 pug 模板,您需要先安装几个 webpack 插件。

  1. htmlwebpack plugin
  2. pug-loader

使用 htmlwebpack 插件,您可以指定您的 pug 模板文件

new HtmlWebpackPlugin({
      template : './index.pug',
      inject   : true
})

pug 模板文件将由 pug-loader 加载。

    {
        test: /\.pug$/,
        include: path.join(__dirname, 'src'),
        loaders: [ 'pug-loader' ]
    },

示例 webpack 配置文件如下所示 -

const path              = require('path');
const webpack           = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');

const isTest = process.env.NODE_ENV === 'test'

module.exports = {

  devtool: 'eval-source-map',

  entry: {
      app: [
          'webpack-hot-middleware/client',
          './src/app.jsx'
      ]
  },
  output: {
    path       : path.join(__dirname, 'public'),
    pathinfo   : true,
    filename   : 'bundle.js',
    publicPath : '/'
  },

  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin(),
    new ExtractTextPlugin("style.css", { allChunks:false }),
    isTest ? undefined : new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
    }),
    new HtmlWebpackPlugin({
          template : './index.pug',
          inject   : true
    })
  ].filter(p => !!p),

  resolve: {
    extensions: ['', '.json', '.js', '.jsx']
  },

  module: {
    loaders: [
        {
            test    : /\.jsx?$/,
            loader  : 'babel',
            exclude : /node_modules/,
            include : path.join(__dirname, 'src')
        },
        {
            test    : /\.scss?$/,
            loader  : ExtractTextPlugin.extract("style-loader", "css-loader!autoprefixer-loader!sass-loader"),
            include : path.join(__dirname, 'sass')
        },
        {
            test    : /\.png$/,
            loader  : 'file'
        },
        {
            test    : /\.(ttf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/,
            loader  : 'file'
        },
        {
            test: /\.pug$/,
            include: path.join(__dirname, 'src'),
            loaders: [ 'pug-loader' ]
        },
        {
            include : /\.json$/,
            loaders : ["json-loader"]
        }
    ]
  }
}