css-loader往CSS中添加了[hash],但是html中没有添加对应的hash,导致两者对应不上

新手上路,请多包涵

问题出现的环境背景及自己尝试过哪些方法

目前在整理自己的学习目录时碰到一个问题:使用css-loader中localIdentName: [name]__[local]--[hash:base64:5]为样式添加hash等,最后添加成功了,但是HTML模版里的却没有添加成功。只能使用[local]了。
也使用了HtmlWebpackPlugin,但是无效

图片描述

相关代码

webpack.base.js

const path = require('path'); 
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin')

module.exports = {
  context: path.resolve(__dirname, '../../'),
  output: {
    publicPath: './',
    path: path.resolve(__dirname, '../../dist'), // 打包后的文件存放的地方
    filename: '[name].[hash:8].js'// 打包后输出文件的文件名
  },
  resolve: {
    extensions: ['.js', '.vue', '.json'],
    alias: {
      vue$: 'vue/dist/vue.esm.js',
      '@': path.resolve('src')
    }
  },
  module: {
    rules: [
      {
        test: /(\.html|\.xml)$/,
        use: [
          {
            loader: 'html-loader',
          }
        ],
        exclude: /node_modules/
      },
      {
        test: /(\.jsx|\.js)$/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: [
              'env',
              'react'
            ]
          }
        },
        exclude: /node_modules/
      },
      {
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: "[name].[hash:7].[ext]",
          publicPath: "./images/", // 打包后CSS引入的基础路径
          outputPath: "images/" // 打包后输出目录
        }
      },
      {
        test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: 'media/[name].[hash:7].[ext]'
        }
      },
      {
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: 'fonts/[name].[hash:7].[ext]'
        }
      }
    ]
  },
  plugins: [
    new OptimizeCSSAssetsPlugin({}),
  ],
};

webpack.pro.js

const webpack = require('webpack');
const program = require('commander');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const path = require('path');
const baseConfig = require('../config/webpack.base.config');
const merge = require('webpack-merge');
const ora = require('ora');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

const spinner = ora({
  spinner: {
    frames:['←','↑','→','↓'],
    interval: 80,
  },
  color: 'red',
  text: 'Loading...',
});

program
  .command('project <project> [file]')
  .action((project, file) => {
    const entry = path.resolve(__dirname, '../../', 'projects', project, file, 'main.js');
    const inlineConfig = merge(baseConfig, {
      entry: function setEntry() {
        return entry; // 入口文件
      },
      mode: 'production',
      module: {
        rules: [
          {
            test: /\.(sa|sc|c)ss$/,
            use: [
              {
                loader: "style-loader"
              },
              {
                loader: MiniCssExtractPlugin.loader,
              },
              {
                loader: "css-loader",
                options: {
                  modules: true, // 指定使用CSS modules
                  localIdentName: '[name]__[local]--[hash:base64:5]' // 指定css的类名格式
                }
              },
              {
                loader: "postcss-loader",
                options: {           // 如果没有options这个选项将会报错 No PostCSS Config found
                  config: {
                    path: './'
                  }
              }
              }
            ]
          }
        ]
      },
      plugins: [
        new MiniCssExtractPlugin({
          filename: "[name].[chunkhash:8].css",
          chunkFilename: "[id].css"
        }),
        new HtmlWebpackPlugin({
          template: path.resolve(__dirname,'../../', 'projects', project, file, 'index.html'),// template
          minify: {
              removeAttributeQuotes:true
            },
            hash: true,
            filename:'index.html'
        }),
        new FriendlyErrorsPlugin({
          compilationSuccessInfo: {
            messages: ['Your application build successed\n'],
          },
        }),
        new CleanWebpackPlugin('../../dist', {
          root: __dirname,
          verbose: true,
          dry: false
        })
      ],
    });
    spinner.start();
    webpack(inlineConfig, (err, stats) => {
      spinner.stop();
      if (err) {
        console.log(err);
      }
      console.log('build successed');
    });
  });

program.parse(process.argv);

webpack.dev.js

const webpack = require('webpack');
const program = require('commander');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin');
const path = require('path');
const baseConfig = require('../config/webpack.base.config');
const serverConfig = require('../server/devServer');
const merge = require('webpack-merge');
const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');
const express = require('express');
const opn = require('opn');

const app = express();

let entry;

program
  .command('project <project> [file]')
  .action((project, file) => {
    entry = path.resolve(__dirname, '../../', 'projects', project, file, 'main.js');
    const inlineConfig = merge(baseConfig, {
      entry: function setEntry() {
        return [entry, 'webpack-hot-middleware/client?reload=true']; // 入口文件
      },
      mode: 'development',
      devtool: 'source-map',
      devServer: serverConfig,
      module: {
        rules: [
          {
            test: /\.(sa|sc|c)ss$/,
            use: [
              {
                loader: "style-loader"
              },
              {
                loader: "css-loader",
                options: {
                  modules: true, // 指定使用CSS modules
                  localIdentName: '[name]__[local]--[hash:base64:5]' // 指定css的类名格式
                }
              },
              {
                loader: "postcss-loader",
                options: {           // 如果没有options这个选项将会报错 No PostCSS Config found
                  config: {
                    path: './'
                  }
              }
              }
            ]
          }
        ]
      },
      plugins: [
        new webpack.HotModuleReplacementPlugin(),
        new FriendlyErrorsPlugin({
          compilationSuccessInfo: {
            messages: [`Your application is running: http://${serverConfig.host}:${serverConfig.port}\n`],
          },
        }),
        new HtmlWebpackPlugin({
          template: path.resolve(__dirname,'../../', 'projects', project, file, 'index.html')// template
        }),
      ],
    });
    const compiler = webpack(inlineConfig);

    app.use(webpackDevMiddleware(compiler, {
      logLevel: 'error',
      progress: true,
      logTime: true,
    }));
    app.use(webpackHotMiddleware(compiler, {
      noInfo: true,
      log: false,
      heartbeat: 2000,
    }));
    app.listen(3000);
    // opn('http://localhost:3000');
  });

program.parse(process.argv);
阅读 3.3k
1 个回答
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题