Skip to content

add support for webpack's new contenthash support #59

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Mar 28, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .gitattributes
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
package-lock.json -diff
* text=auto
bin/* eol=lf
test/cases/* eol=lf
bin/* eol=lf
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,11 @@ When inlining CSS `data-href` must be used.
<tbody>
</table>

#### Long Term Caching

For long term caching use `filename: "[contenthash].css"`. Optionally add `[name]`.


[npm]: https://img.shields.io/npm/v/mini-css-extract-plugin.svg
[npm-url]: https://npmjs.com/package/mini-css-extract-plugin

Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@
"nsp": "^3.1.0",
"pre-commit": "^1.2.2",
"standard-version": "^4.3.0",
"webpack": "^4.1.0",
"webpack": "^4.3.0",
"webpack-cli": "^2.0.13",
"webpack-defaults": "^1.6.0",
"webpack-dev-server": "^3.1.1"
Expand All @@ -56,7 +56,7 @@
"node": ">= 6.11.5"
},
"peerDependencies": {
"webpack": "^4.1.0"
"webpack": "^4.3.0"
},
"pre-commit": "lint-staged",
"lint-staged": {
Expand Down
51 changes: 48 additions & 3 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import webpack from 'webpack';
import sources from 'webpack-sources';

const { ConcatSource, SourceMapSource, OriginalSource } = sources;
const { Template } = webpack;
const { Template, util: { createHash } } = webpack;

const NS = path.dirname(fs.realpathSync(__filename));

Expand Down Expand Up @@ -57,7 +57,7 @@ class CssModule extends webpack.Module {
nameForCondition() {
const resource = this._identifier.split('!').pop();
const idx = resource.indexOf('?');
if (idx >= 0) return resource.substr(0, idx);
if (idx >= 0) return resource.substring(0, idx);
return resource;
}

Expand All @@ -66,6 +66,13 @@ class CssModule extends webpack.Module {
this.buildMeta = {};
callback();
}

updateHash(hash) {
super.updateHash(hash);
hash.update(this.content);
hash.update(this.media || '');
hash.update(JSON.stringify(this.sourceMap || ''));
}
}

class CssModuleFactory {
Expand Down Expand Up @@ -121,6 +128,7 @@ class MiniCssExtractPlugin {
filenameTemplate: this.options.filename,
pathOptions: {
chunk,
contentHashType: NS,
},
identifier: `mini-css-extract-plugin.${chunk.id}`,
});
Expand All @@ -134,11 +142,26 @@ class MiniCssExtractPlugin {
filenameTemplate: this.options.chunkFilename,
pathOptions: {
chunk,
contentHashType: NS,
},
identifier: `mini-css-extract-plugin.${chunk.id}`,
});
}
});
compilation.hooks.contentHash.tap(pluginName, (chunk) => {
const { outputOptions } = compilation;
const { hashFunction, hashDigest, hashDigestLength } = outputOptions;
const hash = createHash(hashFunction);
for (const m of chunk.modulesIterable) {
if (m.type === NS) {
m.updateHash(hash);
}
}
const { contentHash } = chunk;
contentHash[NS] = hash
.digest(hashDigest)
.substring(0, hashDigestLength);
});
const { mainTemplate } = compilation;
mainTemplate.hooks.localVars.tap(
pluginName,
Expand Down Expand Up @@ -178,13 +201,35 @@ class MiniCssExtractPlugin {
const shortChunkHashMap = Object.create(null);
for (const chunkId of Object.keys(chunkMaps.hash)) {
if (typeof chunkMaps.hash[chunkId] === 'string') {
shortChunkHashMap[chunkId] = chunkMaps.hash[chunkId].substr(0, length);
shortChunkHashMap[chunkId] = chunkMaps.hash[chunkId].substring(0, length);
}
}
return `" + ${JSON.stringify(shortChunkHashMap)}[chunkId] + "`;
},
contentHash: {
[NS]: `" + ${JSON.stringify(
chunkMaps.contentHash[NS],
)}[chunkId] + "`,
},
contentHashWithLength: {
[NS]: (length) => {
const shortContentHashMap = {};
const contentHash = chunkMaps.contentHash[NS];
for (const chunkId of Object.keys(contentHash)) {
if (typeof contentHash[chunkId] === 'string') {
shortContentHashMap[chunkId] = contentHash[
chunkId
].substring(0, length);
}
}
return `" + ${JSON.stringify(
shortContentHashMap,
)}[chunkId] + "`;
},
},
name: `" + (${JSON.stringify(chunkMaps.name)}[chunkId]||chunkId) + "`,
},
contentHashType: NS,
},
);
return Template.asString([
Expand Down
17 changes: 10 additions & 7 deletions test/TestCases.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,16 @@ describe('TestCases', () => {
const outputDirectoryForCase = path.resolve(outputDirectory, directory);
// eslint-disable-next-line import/no-dynamic-require, global-require
const webpackConfig = require(path.resolve(directoryForCase, 'webpack.config.js'));
webpack(Object.assign({
mode: 'none',
context: directoryForCase,
output: {
path: outputDirectoryForCase,
},
}, webpackConfig), (err, stats) => {
for (const config of [].concat(webpackConfig)) {
Object.assign(config, {
mode: 'none',
context: directoryForCase,
output: Object.assign({
path: outputDirectoryForCase,
}, config.output),
}, config);
}
webpack(webpackConfig, (err, stats) => {
if (err) {
done(err);
return;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
body { background: red; }

Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
body { background: green; }

1 change: 1 addition & 0 deletions test/cases/contenthash/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
import './style.css';
1 change: 1 addition & 0 deletions test/cases/contenthash/style1.css
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
body { background: red; }
1 change: 1 addition & 0 deletions test/cases/contenthash/style2.css
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
body { background: green; }
29 changes: 29 additions & 0 deletions test/cases/contenthash/webpack.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
const Self = require('../../../');

module.exports = [1, 2].map(n => ({
entry: './index.js',
module: {
rules: [
{
test: /\.css$/,
use: [
Self.loader,
'css-loader',
],
},
],
},
output: {
filename: `${n}.[name].js`
},
resolve: {
alias: {
'./style.css': `./style${n}.css`
}
},
plugins: [
new Self({
filename: `${n}.[name].[contenthash].css`,
}),
],
}));
10 changes: 10 additions & 0 deletions test/cases/js-hash/expected/style.41bf047ed4fa005a3e24.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
(window["webpackJsonp"] = window["webpackJsonp"] || []).push([[1],[
/* 0 */,
/* 1 */
/***/ (function(module, exports, __webpack_require__) {

// extracted by mini-css-extract-plugin
module.exports = {"a":"wX52cuPepLZcpDx5S3yYO"};

/***/ })
]]);
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.wX52cuPepLZcpDx5S3yYO { background: red; }
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The double hashes in the filename look scary 🤔

I assume that actual users will want to use [contenthash] only instead of both [contenthash] and [chunkhash]

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes of course, this is just a test which tests both

Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.wX52cuPepLZcpDx5S3yYO { background: green; }
1 change: 1 addition & 0 deletions test/cases/js-hash/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
import(/* webpackChunkName: "style" */'./style.css');
4 changes: 4 additions & 0 deletions test/cases/js-hash/loader.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
module.exports = function(source) {
const { number } = this.query;
return source.split(/\r?\n/)[number-1];
};
2 changes: 2 additions & 0 deletions test/cases/js-hash/style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
.a { background: red; }
.a { background: green; }
36 changes: 36 additions & 0 deletions test/cases/js-hash/webpack.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
const Self = require('../../../');

module.exports = [1, 2].map(n => ({
entry: './index.js',
module: {
rules: [
{
test: /\.css$/,
use: [
Self.loader,
{
loader: 'css-loader',
options: {
modules: true,
},
},
{
loader: './loader',
ident: 'my-loader',
options: {
number: n
}
}
],
},
],
},
output: {
filename: `[name].[contenthash].js`
},
plugins: [
new Self({
filename: `[name].[contenthash].[chunkhash].css`,
}),
],
}));
22 changes: 11 additions & 11 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1327,7 +1327,7 @@ cac@^3.0.3:
suffix "^0.1.0"
text-table "^0.2.0"

cacache@^10.0.1:
cacache@^10.0.4:
version "10.0.4"
resolved "https://registry.yarnpkg.com/cacache/-/cacache-10.0.4.tgz#6452367999eff9d4188aefd9a14e9d7c6a263460"
dependencies:
Expand Down Expand Up @@ -6922,7 +6922,7 @@ sax@^1.2.4, sax@~1.2.1:
version "1.2.4"
resolved "https://registry.yarnpkg.com/sax/-/sax-1.2.4.tgz#2816234e2378bddc4e5354fab5caa895df7100d9"

schema-utils@^0.4.2:
schema-utils@^0.4.2, schema-utils@^0.4.5:
version "0.4.5"
resolved "https://registry.yarnpkg.com/schema-utils/-/schema-utils-0.4.5.tgz#21836f0608aac17b78f9e3e24daff14a5ca13a3e"
dependencies:
Expand Down Expand Up @@ -7724,13 +7724,13 @@ uglify-to-browserify@~1.0.0:
version "1.0.2"
resolved "https://registry.yarnpkg.com/uglify-to-browserify/-/uglify-to-browserify-1.0.2.tgz#6e0924d6bda6b5afe349e39a6d632850a0f882b7"

uglifyjs-webpack-plugin@^1.1.1:
version "1.2.2"
resolved "https://registry.yarnpkg.com/uglifyjs-webpack-plugin/-/uglifyjs-webpack-plugin-1.2.2.tgz#e7516d4367afdb715c3847841eb46f94c45ca2b9"
uglifyjs-webpack-plugin@^1.2.4:
version "1.2.4"
resolved "https://registry.yarnpkg.com/uglifyjs-webpack-plugin/-/uglifyjs-webpack-plugin-1.2.4.tgz#5eec941b2e9b8538be0a20fc6eda25b14c7c1043"
dependencies:
cacache "^10.0.1"
cacache "^10.0.4"
find-cache-dir "^1.0.0"
schema-utils "^0.4.2"
schema-utils "^0.4.5"
serialize-javascript "^1.4.0"
source-map "^0.6.1"
uglify-es "^3.3.4"
Expand Down Expand Up @@ -8125,9 +8125,9 @@ webpack-sources@^1.0.1, webpack-sources@^1.1.0:
source-list-map "^2.0.0"
source-map "~0.6.1"

webpack@^4.1.0:
version "4.1.0"
resolved "https://registry.yarnpkg.com/webpack/-/webpack-4.1.0.tgz#91b6862e56eb3b18b79bb10b51866987ff10d2d6"
webpack@^4.3.0:
version "4.3.0"
resolved "https://registry.yarnpkg.com/webpack/-/webpack-4.3.0.tgz#0b0c1e211311b3995dd25aed47ab46ea658be070"
dependencies:
acorn "^5.0.0"
acorn-dynamic-import "^3.0.0"
Expand All @@ -8145,7 +8145,7 @@ webpack@^4.1.0:
node-libs-browser "^2.0.0"
schema-utils "^0.4.2"
tapable "^1.0.0"
uglifyjs-webpack-plugin "^1.1.1"
uglifyjs-webpack-plugin "^1.2.4"
watchpack "^1.5.0"
webpack-sources "^1.0.1"

Expand Down