Skip to content

Add support changes Webpack 5 compiler API #51

New issue

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

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

Already on GitHub? # to your account

Merged
merged 4 commits into from
Jan 1, 2021
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
61 changes: 47 additions & 14 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@ const glob = require('glob');
const { promisify } = require('es6-promisify');
const revHash = require('rev-hash');

const plugin = { name: 'MergeIntoFile' };

const webpackMajorVersion = Number(require('webpack/package.json').version.split('.')[0]);

const readFile = promisify(fs.readFile);
const listFiles = promisify(glob);

Expand All @@ -17,8 +21,14 @@ class MergeIntoFile {

apply(compiler) {
if (compiler.hooks) {
const plugin = { name: 'MergeIntoFile' };
compiler.hooks.emit.tapAsync(plugin, this.run.bind(this));
if (webpackMajorVersion < 5) {
compiler.hooks.emit.tapAsync(plugin, this.run.bind(this));
} else {
compiler.hooks.compilation.tap(plugin, this.run.bind(this));
Copy link

Choose a reason for hiding this comment

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

This should be thisCompilation instead of compilation I guess, see FormidableLabs/webpack-stats-plugin#52 (comment)

Copy link
Contributor Author

@igk1972 igk1972 Jan 2, 2021

Choose a reason for hiding this comment

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

Copy link
Owner

Choose a reason for hiding this comment

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

@kelunik changed & published, thanks

Copy link

Choose a reason for hiding this comment

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

Thanks!

compiler.hooks.failed.tap(plugin, error => {
throw new Error(error);
});
}
} else {
compiler.plugin('emit', this.run.bind(this));
}
Expand Down Expand Up @@ -49,8 +59,10 @@ class MergeIntoFile {
transformFileName,
} = this.options;
if (chunks && compilation.chunks && compilation.chunks
.filter((chunk) => chunks.indexOf(chunk.name) >= 0 && chunk.rendered).length === 0) {
callback();
.filter(chunk => chunks.indexOf(chunk.name) >= 0 && chunk.rendered).length === 0) {
if (typeof(callback) === 'function') {
callback();
}
return;
}
const generatedFiles = {};
Expand Down Expand Up @@ -115,14 +127,27 @@ class MergeIntoFile {
}
}
generatedFiles[newFileName] = newFileNameHashed;
compilation.assets[newFileNameHashed] = { // eslint-disable-line no-param-reassign
source() {
return resultsFiles[newFileName];
},
size() {
return resultsFiles[newFileName].length;
},
};
if (compilation.hooks) {
const { sources, Compilation } = require('webpack');
compilation.hooks.processAssets.tap(
{
name: plugin.name,
stage: Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL,
},
() => {
compilation.emitAsset(newFileNameHashed, new sources.RawSource(resultsFiles[newFileName]))
}
);
} else {
compilation.assets[newFileNameHashed] = { // eslint-disable-line no-param-reassign
source() {
return resultsFiles[newFileName];
},
size() {
return resultsFiles[newFileName].length;
},
};
}
});
});

Expand All @@ -131,9 +156,17 @@ class MergeIntoFile {
if (this.onComplete) {
this.onComplete(generatedFiles);
}
callback();
if (typeof(callback) === 'function') {
callback();
}
})
.catch((error) => callback(error));
.catch(error => {
if (typeof(callback) === 'function') {
callback(error);
} else {
throw new Error(error);
}
});
}
}

Expand Down
227 changes: 91 additions & 136 deletions index.node6-compatible.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,12 @@ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefau

var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));

var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));
const plugin = { name: 'MergeIntoFile' };

const webpackMajorVersion = Number(require('webpack/package.json').version.split('.')[0]);

const readFile = promisify(fs.readFile);
const listFiles = promisify(glob);

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

Expand Down Expand Up @@ -106,17 +111,18 @@ var MergeIntoFile = /*#__PURE__*/function () {
this.onComplete = onComplete;
}

(0, _createClass2["default"])(MergeIntoFile, [{
key: "apply",
value: function apply(compiler) {
if (compiler.hooks) {
var plugin = {
name: 'MergeIntoFile'
};
apply(compiler) {
if (compiler.hooks) {
if (webpackMajorVersion < 5) {
compiler.hooks.emit.tapAsync(plugin, this.run.bind(this));
} else {
compiler.plugin('emit', this.run.bind(this));
compiler.hooks.compilation.tap(plugin, this.run.bind(this));
compiler.hooks.failed.tap(plugin, error => {
throw new Error(error);
});
}
} else {
compiler.plugin('emit', this.run.bind(this));
}
}, {
key: "run",
Expand All @@ -138,15 +144,40 @@ var MergeIntoFile = /*#__PURE__*/function () {
return;
}

var generatedFiles = {};
var filesCanonical = [];

if (!Array.isArray(files)) {
Object.keys(files).forEach(function (newFile) {
filesCanonical.push({
src: files[newFile],
dest: newFile
});
run(compilation, callback) {
var _this = this;

const {
files,
transform,
encoding,
chunks,
hash,
transformFileName
} = this.options;
if (chunks && compilation.chunks && compilation.chunks.filter(chunk => chunks.indexOf(chunk.name) >= 0 && chunk.rendered).length === 0) {
if (typeof callback === 'function') {
callback();
}
return;
}
const generatedFiles = {};
let filesCanonical = [];
if (!Array.isArray(files)) {
Object.keys(files).forEach(newFile => {
filesCanonical.push({
src: files[newFile],
dest: newFile
});
});
} else {
filesCanonical = files;
}
filesCanonical.forEach(fileTransform => {
if (typeof fileTransform.dest === 'string') {
const destFileName = fileTransform.dest;
fileTransform.dest = code => ({ // eslint-disable-line no-param-reassign
[destFileName]: transform && transform[destFileName] ? transform[destFileName](code) : code
});
} else {
filesCanonical = files;
Expand Down Expand Up @@ -175,115 +206,33 @@ var MergeIntoFile = /*#__PURE__*/function () {
return listFiles(path, null);
}));

case 3:
listOfLists = _context4.sent;
flattenedList = Array.prototype.concat.apply([], listOfLists);
filesContentPromises = flattenedList.map(function (path) {
return readFile(path, encoding || 'utf-8');
});
_context4.next = 8;
return joinContent(filesContentPromises, separator);

case 8:
content = _context4.sent;
_context4.next = 11;
return fileTransform.dest(content);

case 11:
resultsFiles = _context4.sent;
Object.keys(resultsFiles).map( /*#__PURE__*/function () {
var _ref5 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(resultsFile) {
return _regenerator["default"].wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
if (!((0, _typeof2["default"])(resultsFiles[resultsFile]) === 'object')) {
_context3.next = 4;
break;
}

_context3.next = 3;
return resultsFiles[resultsFile];

case 3:
resultsFiles[resultsFile] = _context3.sent;

case 4:
case "end":
return _context3.stop();
}
}
}, _callee3);
}));

return function (_x6) {
return _ref5.apply(this, arguments);
};
}());
Object.keys(resultsFiles).forEach(function (newFileName) {
var newFileNameHashed = newFileName;
var hasTransformFileNameFn = typeof transformFileName === 'function';

if (hash || hasTransformFileNameFn) {
var hashPart = MergeIntoFile.getHashOfRelatedFile(compilation.assets, newFileName) || revHash(resultsFiles[newFileName]);

if (hasTransformFileNameFn) {
var extensionPattern = /\.[^.]*$/g;
var fileNameBase = newFileName.replace(extensionPattern, '');

var _newFileName$match = newFileName.match(extensionPattern),
_newFileName$match2 = (0, _slicedToArray2["default"])(_newFileName$match, 1),
extension = _newFileName$match2[0];

newFileNameHashed = transformFileName(fileNameBase, extension, hashPart);
} else {
newFileNameHashed = newFileName.replace(/(\.min)?\.\w+(\.map)?$/, function (suffix) {
return "-".concat(hashPart).concat(suffix);
});
}

var fileId = newFileName.replace(/\.map$/, '').replace(/\.\w+$/, '');

if (typeof compilation.addChunk === 'function') {
var chunk = compilation.addChunk(fileId);
chunk.id = fileId;
chunk.ids = [chunk.id];
chunk.files.push(newFileNameHashed);
}
}

generatedFiles[newFileName] = newFileNameHashed;
compilation.assets[newFileNameHashed] = {
// eslint-disable-line no-param-reassign
source: function source() {
return resultsFiles[newFileName];
},
size: function size() {
return resultsFiles[newFileName].length;
}
};
});

case 14:
case "end":
return _context4.stop();
}
if (typeof compilation.addChunk === 'function') {
const chunk = compilation.addChunk(fileId);
chunk.id = fileId;
chunk.ids = [chunk.id];
chunk.files.push(newFileNameHashed);
}
}, _callee4);
}));

return function (_x5) {
return _ref4.apply(this, arguments);
};
}());
Promise.all(finalPromises).then(function () {
if (_this.onComplete) {
_this.onComplete(generatedFiles);
}

callback();
})["catch"](function (error) {
return callback(error);
}
generatedFiles[newFileName] = newFileNameHashed;
if (compilation.hooks) {
const { sources, Compilation } = require('webpack');
compilation.hooks.processAssets.tap({
name: plugin.name,
stage: Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL
}, function () {
compilation.emitAsset(newFileNameHashed, new sources.RawSource(resultsFiles[newFileName]));
});
} else {
compilation.assets[newFileNameHashed] = { // eslint-disable-line no-param-reassign
source() {
return resultsFiles[newFileName];
},
size() {
return resultsFiles[newFileName].length;
}
};
}
});
});
}
}], [{
Expand All @@ -297,15 +246,21 @@ var MergeIntoFile = /*#__PURE__*/function () {
if (fileHashPart) {
var canonicalFileName = existingFileName.replace("-".concat(fileHashPart), '').replace(/\.map$/, '');

if (canonicalFileName === fileName.replace(/\.map$/, '')) {
hashPart = fileHashPart;
}
}
});
return hashPart;
}
}]);
return MergeIntoFile;
}();
Promise.all(finalPromises).then(() => {
if (this.onComplete) {
this.onComplete(generatedFiles);
}
if (typeof callback === 'function') {
callback();
}
}).catch(error => {
if (typeof callback === 'function') {
callback(error);
} else {
throw new Error(error);
}
});
}
}

module.exports = MergeIntoFile;