0

问题的本质是:有一个基于 webpack 的构建,一切正常,但有一个例外:更改 PUG 文件时。项目已重建,但内容未在浏览器中更新。构建时会产生错误:Entrypoint undefined = ./index.html

    const path = require('path');
const fs = require('fs');
const HTMLWebpackPlugin = require('html-webpack-plugin');
const {CleanWebpackPlugin} = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCssAssetWebpackPlugin = require('optimize-css-assets-webpack-plugin');
const TerserWebpackPlugin = require('terser-webpack-plugin');


const PATHS = {
  src: path.join(__dirname, './src'),
  dist: path.join(__dirname, './dist'),
  assets: 'assets/',
  pages: function () { return `${this.src}/pug/` }
}

// const PAGES_DIR = PATHS.src
const PAGES = fs.readdirSync(PATHS.pages()).filter(fileName => fileName.endsWith('.pug'));

const isDev = process.env.NODE_ENV === 'development'
const isProd = !isDev

const optimization = () => {
  const config = {
    splitChunks: {
      chunks: 'all'
    }
  }

  if (isProd) {
    config.minimizer = [
      new OptimizeCssAssetWebpackPlugin(),
      new TerserWebpackPlugin()
    ]
  }

  return config
}

const filename = ext => isDev ? `[name].${ext}` : `[name].[hash].${ext}`

const cssLoaders = extra => {
  const loaders = [
    {
      loader: MiniCssExtractPlugin.loader,
      options: {
        hmr: isDev,
        reloadAll: true
      },
    },
    'css-loader'
  ]

  if (extra) {
    loaders.push(extra)
  }

  return loaders
}

const babelOptions = preset => {
  const opts = {
    presets: [
      '@babel/preset-env'
    ],
    plugins: [
      '@babel/plugin-proposal-class-properties'
    ]
  }

  if (preset) {
    opts.presets.push(preset)
  }

  return opts
}

const jsLoaders = () => {
  const loaders = [{
    loader: 'babel-loader',
    options: babelOptions()
  }]

  if (isDev) {
    loaders.push('eslint-loader')
  }

  return loaders
}

const plugins = () => {
  const base = [
    new CleanWebpackPlugin(),
    new CopyWebpackPlugin([
      { from: `${PATHS.src}/${PATHS.assets}img`, to: `${PATHS.assets}img` },
      { from: `${PATHS.src}/${PATHS.assets}fonts`, to: `${PATHS.assets}fonts` },
      { from: `${PATHS.src}/static`, to: '' },
    ]),
    new MiniCssExtractPlugin({
      filename: filename('css')
    }),
    ...PAGES.map(page => new HTMLWebpackPlugin({
      template: `${PATHS.pages()}/${page}`,
      filename: `./${page.replace(/\.pug/,'.html')}`,
    }))
  ]


  return base
}

module.exports = {
  context: PATHS.src,
  mode: process.env.NODE_ENV,
  entry: {
    app: PATHS.src,
  },
  output: {
    filename: filename('js'),
    path: PATHS.dist
  },
  resolve: {
    extensions: ['.js', '.json', '.png'],
    alias: {
      '@': PATHS.src,
    }
  },
  optimization: optimization(),
  devServer: {
    hot: isDev
  },
  devtool: isDev ? 'source-map' : '',
  plugins: plugins(),
  module: {
    rules: [
      {
        test: /\.pug$/,
        loader: 'pug-loader',
        options: {
          pretty: isProd
        }
      },
      {
        test: /\.css$/,
        use: cssLoaders()
      },
      {
        test: /\.s[ac]ss$/,
        use: cssLoaders('sass-loader')
      },
      {
        test: /\.(png|jpg|svg|gif)$/,
        use: ['file-loader']
      },
      {
        test: /\.(ttf|woff|woff2|eot)$/,
        use: ['file-loader']
      },
      {
        test: /\.xml$/,
        use: ['xml-loader']
      },
      {
        test: /\.csv$/,
        use: ['csv-loader']
      },
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: jsLoaders()
      }
    ]
  }
}

项目结构: 此处输入图片描述

4

2 回答 2

0

你试过html-webpack-pug-plugin吗?

npm i html-webpack-pug-plugin

替换这个:

const plugins = () => {
    const base = [
        //..
        ...PAGES.map(page => new HTMLWebpackPlugin({
            template: `${PATHS.pages()}/${page}`,
            filename: `./${page.replace(/\.pug/, '.html')}`,
        }))
    ]
//...

有了这个:

const plugins = () => {
    const base = [
        //..
        new HtmlWebpackPugPlugin(),
        new HtmlWebpackPlugin({
            template: './src/pug/index.pug',
            filename: 'index.pug',
        })
    ]
//...

index.pug该插件将参考js和css文件将主文件复制到dist目录中。

然后静态目录中的 pug 文件应该像这样加载主模板文件:

extends ../../dist/index.pug
于 2020-10-06T19:43:17.043 回答
0

我已经通过附加包chokidar解决了这个问题。

我使用下一个代码:

    const chokidar = require('chokidar');
   ...
  devServer: {
    hot: true,
    overlay: {
      warnings: false,
      errors: true
    },
    before(app, server) {
      chokidar.watch([
        `${PATHS.src}/**/*.pug`
      ]).on('all', function() {
        server.sockWrite(server.sockets, 'content-changed');
      })
    }
  }
   ...
于 2020-10-09T07:19:08.000 回答