如何修复Webpack Dev Server不被忽略的HTML文件注释?

时间:2017-09-10 18:11:08

标签: webpack webpack-dev-server webpack-html-loader

我使用webpack进行html-loader(v3.5.6)构建,并将多个HTML文件自行处理,使用url-loader将较小的图片嵌入到HTML中。配置完全适合构建,但在使用Webpack Dev Server(v2.7.1)时失败,因为Webpack Dev Server似乎不会忽略源HTML文件中的注释。它尝试从HTML的注释部分中获取资源,并且此时某些资源不存在。

以下是来自Webpack Dev Server的示例错误:

ERROR in ./about-us.html
Module not found: Error: Can't resolve './img/old-image.png' in 'C:\Users\usr\dev\www'
 @ ./about-us.html
 @ ./entry.js
 @ multi (webpack)-dev-server/client?http://localhost:8080 ./entry.js

我的(未完成的)webpack配置如下:

webpack.common.js

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

const CleanWebpackPlugin = require('clean-webpack-plugin');

const env = process.env.NODE_ENV;

module.exports = {
  entry: './entry.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js'
  },
  module: {
    rules: [{
        test: /\.html$/,
        use: [
          {
            loader: 'file-loader',
            options: {
              name: '[name].[ext]',
            },
          },
          {
            loader: 'extract-loader',
          },
          {
            loader: 'html-loader',
            options: {
              attrs: ['img:src'],
              interpolate: true,
            },
          },
        ],
      },
      {
        test: /\.js$/,
        exclude: /(node_modules)/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['env']
          }
        }
      },
      {
        test: /\.css$/,
        use: env === 'production' ?
          ExtractTextPlugin.extract({
            fallback: 'style-loader',
            use: ['css-loader']
          }) : ['style-loader', 'css-loader']
      },
      {
        test: /\.(png|jpg|gif|svg)$/,
        use: [{
          loader: 'url-loader',
          options: {
            limit: 8192,
            name: '[path][name].[ext]'
          }
        }]
      }
    ]
  },
  resolve: {
    alias: {
      'vue$': 'vue/dist/vue.common.js',
    },
  },
  plugins: [
    new CleanWebpackPlugin(['dist', 'build'])
  ],
};

webpack.dev.js

const merge = require('webpack-merge');

const common = require('./webpack.common.js');

module.exports = merge(common, {
  devServer: {
    contentBase: './dist'
  },
});

webpack.prod.js:

const merge = require('webpack-merge');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
const ExtractTextPlugin = require("extract-text-webpack-plugin");

const common = require('./webpack.common.js');

module.exports = merge(common, {
  plugins: [
    new UglifyJSPlugin(),
    new ExtractTextPlugin({
      filename: 'styles.css'
    })
  ]
});

entry.js:

require('./about-us.html');
require('./index.html');
require('./css/style.css');
require('./js/sidebar.js');

1 个答案:

答案 0 :(得分:2)

您必须在html-loader的配置中激活评论缩小。

'innerarray