Skip to content

Commit 228c9ee

Browse files
authored
Merge pull request #1 from chenxsan/add-contenthash-support
Add contenthash support
2 parents 438c81e + db8d63a commit 228c9ee

File tree

6 files changed

+40
-1
lines changed

6 files changed

+40
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ module.exports = {
4848
new MiniCssExtractPlugin({
4949
// Options similar to the same options in webpackOptions.output
5050
// both options are optional
51-
filename: "[name].css",
51+
filename: "[name].css", // [contenthash] is supported
5252
chunkFilename: "[id].css"
5353
})
5454
],

src/index.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import fs from 'fs';
22
import path from 'path';
33
import webpack from 'webpack';
44
import sources from 'webpack-sources';
5+
import loaderUtils from 'loader-utils';
56

67
const { ConcatSource, SourceMapSource, OriginalSource } = sources;
78
const { Template } = webpack;
@@ -95,6 +96,19 @@ class MiniCssExtractPlugin {
9596
}
9697

9798
apply(compiler) {
99+
// add contenthash support
100+
compiler.hooks.emit.tap(pluginName, (compilation) => {
101+
const regexp = /\[(?:(\w+):)?contenthash(?::([a-z]+\d*))?(?::(\d+))?\]/ig;
102+
Object.keys(compilation.assets).forEach((filename) => {
103+
if (regexp.test(filename)) {
104+
const source = compilation.assets[filename].source();
105+
const getHashDigest = (...args) => loaderUtils.getHashDigest(source, args[1], args[2], parseInt(args[3], 10));
106+
const newFilename = filename.replace(regexp, getHashDigest);
107+
compilation.assets[newFilename] = compilation.assets[filename]; // eslint-disable-line no-param-reassign
108+
delete compilation.assets[filename]; // eslint-disable-line no-param-reassign
109+
}
110+
});
111+
});
98112
compiler.hooks.thisCompilation.tap(pluginName, (compilation) => {
99113
compilation.hooks.normalModuleLoader.tap(pluginName, (lc, m) => {
100114
const loaderContext = lc;
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
body { background: red; }
2+
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
import './style.css';
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
body { background: red; }
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
const Self = require('../../../');
2+
3+
module.exports = {
4+
entry: './index.js',
5+
module: {
6+
rules: [
7+
{
8+
test: /\.css$/,
9+
use: [
10+
Self.loader,
11+
'css-loader',
12+
],
13+
},
14+
],
15+
},
16+
plugins: [
17+
new Self({
18+
filename: '[name].[contenthash].css',
19+
}),
20+
],
21+
};

0 commit comments

Comments
 (0)