Skip to content

Instantly share code, notes, and snippets.

@asciidisco
Last active February 3, 2016 17:41
Show Gist options
  • Save asciidisco/b9cb189d1f969e0f3a19 to your computer and use it in GitHub Desktop.
Save asciidisco/b9cb189d1f969e0f3a19 to your computer and use it in GitHub Desktop.
Webpack Plugin Development -> Create a new chunk bundle that gets loaded async -> Replace the old bundles
webpackJsonp([5,2,3],[
/* 0 */,
/* 1 */
/***/ function(module, exports) {
module.exports = {
"notification.licenseExpires": function () {
return function () {
var number = function (value, offset) {
if (isNaN(value)) throw new Error("'" + value + "' isn't a number.");
return value - (offset || 0);
};
var plural = function (value, offset, lcfunc, data, isOrdinal) {
if ({}.hasOwnProperty.call(data, value)) return data[value]();
if (offset) value -= offset;
var key = lcfunc(value, isOrdinal);
if (key in data) return data[key]();
return data.other();
};
var select = function (value, data) {
if ({}.hasOwnProperty.call(data, value)) return data[value]();
return data.other()
};
var pluralFuncs = {
de: function (n
/**/) {
return (n==1) ? "one" : n==0 ? "none" : "other"
}
};
var fmt = {};
return {
"0": {
},
"1": function(d) { return plural(d.NUM, 0, pluralFuncs.de, { one: function() { return "Meldung";}, other: function() { return "Meldungen";} }); }
}
}()[1](arguments[0])
},
};
/***/ },
/* 2 */
/***/ function(module, exports) {
module.exports = {
"test": function () {
return function () {
var number = function (value, offset) {
if (isNaN(value)) throw new Error("'" + value + "' isn't a number.");
return value - (offset || 0);
};
var plural = function (value, offset, lcfunc, data, isOrdinal) {
if ({}.hasOwnProperty.call(data, value)) return data[value]();
if (offset) value -= offset;
var key = lcfunc(value, isOrdinal);
if (key in data) return data[key]();
return data.other();
};
var select = function (value, data) {
if ({}.hasOwnProperty.call(data, value)) return data[value]();
return data.other()
};
var pluralFuncs = {
de: function (n
/**/) {
return (n==1) ? "one" : n==0 ? "none" : "other"
}
};
var fmt = {};
return {
"0": {
},
"1": function(d) { return "It´s a language test"; }
}
}()[1](arguments[0])
},
};
/***/ }
]);
//# sourceMappingURL=de_DE.js.map
main.js
i18n/
-- de_DE
- app.po
- plugin.po
-- en-GB
- app.po
- plugin.po
/******/ (function(modules) { // webpackBootstrap
/******/ // install a JSONP callback for chunk loading
/******/ var parentJsonpFunction = window["webpackJsonp"];
/******/ window["webpackJsonp"] = function webpackJsonpCallback(chunkIds, moreModules, executeModule) {
/******/ // add "moreModules" to the modules object,
/******/ // then flag all "chunkIds" as loaded and fire callback
/******/ var moduleId, chunkId, i = 0, resolves = [];
/******/ for(;i < chunkIds.length; i++) {
/******/ chunkId = chunkIds[i];
/******/ if(installedChunks[chunkId])
/******/ resolves.push(installedChunks[chunkId][0]);
/******/ installedChunks[chunkId] = 0;
/******/ }
/******/ for(moduleId in moreModules) {
/******/ modules[moduleId] = moreModules[moduleId];
/******/ }
/******/ if(parentJsonpFunction) parentJsonpFunction(chunkIds, moreModules);
/******/ while(resolves.length)
/******/ resolves.shift()();
/******/
/******/ };
/******/
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // objects to store loaded and loading chunks
/******/ var installedChunks = {
/******/ 4: 0
/******/ };
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/ // This file contains only the entry chunk.
/******/ // The chunk loading function for additional chunks
/******/ __webpack_require__.e = function requireEnsure(chunkId) {
/******/ if(installedChunks[chunkId] === 0)
/******/ return Promise.resolve()
/******/
/******/ // an Promise means "currently loading".
/******/ if(installedChunks[chunkId]) {
/******/ return installedChunks[chunkId][2];
/******/ }
/******/ // start chunk loading
/******/ var head = document.getElementsByTagName('head')[0];
/******/ var script = document.createElement('script');
/******/ script.type = 'text/javascript';
/******/ script.charset = 'utf-8';
/******/ script.async = true;
/******/ script.timeout = 120000;
/******/
/******/ script.src = __webpack_require__.p + "" + ({}[chunkId]||chunkId) + ".js";
/******/ var timeout = setTimeout(onScriptComplete, 120000);
/******/ script.onerror = script.onload = onScriptComplete;
/******/ function onScriptComplete() {
/******/ // avoid mem leaks in IE.
/******/ script.onerror = script.onload = null;
/******/ clearTimeout(timeout);
/******/ var chunk = installedChunks[chunkId];
/******/ if(chunk !== 0) {
/******/ if(chunk) chunk[1](new Error('Loading chunk ' + chunkId + ' failed.'));
/******/ installedChunks[chunkId] = undefined;
/******/ }
/******/ };
/******/ head.appendChild(script);
/******/
/******/ var promise = new Promise(function(resolve, reject) {
/******/ installedChunks[chunkId] = [resolve, reject];
/******/ });
/******/ return installedChunks[chunkId][2] = promise;
/******/ };
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // on error function for async loading
/******/ __webpack_require__.oe = function(err) { throw err; };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "/";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 7);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var lang = window.foo ? 'en_EN' : 'de_DE';
Promise.all([__webpack_require__(6)("./" + lang + '/plugin.po'), __webpack_require__(5)("./" + lang + '/app.po')]).then(function (data) {
return data.forEach(function (bundle) {
return Object.keys(bundle).forEach(function (item) {
return console.log(bundle[item]({ NUM: 1 }));
});
});
}).catch(function (err) {
return console.log('Chunk loading failed', err);
});
/***/ },
/* 1 */,
/* 2 */,
/* 3 */,
/* 4 */,
/* 5 */
/***/ function(module, exports, __webpack_require__) {
var map = {
"./de_DE/app.po": [
1,
4
],
"./en_GB/app.po": [
3,
1
]
};
function webpackAsyncContext(req) {
var ids = map[req]; if(!ids)
return Promise.reject(new Error("Cannot find module '" + req + "'."));
return __webpack_require__.e(ids[1]).then(function() {
return __webpack_require__(ids[0]);
});
};
webpackAsyncContext.keys = function webpackAsyncContextKeys() {
return Object.keys(map);
};
module.exports = webpackAsyncContext;
webpackAsyncContext.id = 5;
/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {
var map = {
"./de_DE/plugin.po": [
2,
4
],
"./en_GB/plugin.po": [
4,
0
]
};
function webpackAsyncContext(req) {
var ids = map[req]; if(!ids)
return Promise.reject(new Error("Cannot find module '" + req + "'."));
return __webpack_require__.e(ids[1]).then(function() {
return __webpack_require__(ids[0]);
});
};
webpackAsyncContext.keys = function webpackAsyncContextKeys() {
return Object.keys(map);
};
module.exports = webpackAsyncContext;
webpackAsyncContext.id = 6;
/***/ },
/* 7 */
/***/ function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(0);
/***/ }
/******/ ]);
//# sourceMappingURL=main.js.maps
let lang = window.foo ? 'en_EN' : 'de_DE';
Promise.all([
System.import('./i18n/' + lang + '/plugin.po'),
System.import('./i18n/' + lang + '/app.po')])
.then(data => data.forEach((bundle) => Object.keys(bundle).forEach((item) => console.log(bundle[item]({NUM: 1})))))
.catch(err => console.log('Chunk loading failed', err));
function MessageformatGettextBundler(options) {
this.options = {};
this.options.ext = 'po';
}
MessageformatGettextBundler.prototype.apply = function(compiler) {
var opts = this.options;
var LANGUAGE = 'de_DE';
compiler.plugin('this-compilation', function(compilation) {
compilation.plugin(['optimize-chunks', 'optimize-extracted-chunks'], function(chunks) {
var root = this.addChunk();
root.async = true;
chunks.forEach(function(chunk, idx) {
if (!chunk.name && chunk.modules[0].rawRequest.indexOf('.' + opts.ext) !== -1 && chunk.modules[0].rawRequest.indexOf('/' + LANGUAGE + '/') !== -1) {
var usedIds = {};
chunk.modules.forEach(function (module, key) {
if (!usedIds[module.index]) {
root.modules.push(module);
usedIds[module.index] = true;
}
})
}
});
});
});
};
module.exports = MessageformatGettextBundler;

Hey there,

for each System.import (see main.js above), webpack creates a file (1.js, 2.js, 3.js, etc.) & in the compiled version, all of the files get loaded async & the app works. Now I`m trying to write a webpack plugin, that takes all the contents of the tiny 1.js, 2.js... files & combines them into one.

What works:

Using the Plugin code above (see MyPlugin.js), I´m able to filter out all the chunks that I want (language artifacts for a particular language in this case), and creates a new file out of it, that can be loaded async.

What doesn't work: My application still requires the two seperate chunks that were originally created by webpack, but what I actually want is, that it only requires the de_DE.js file.

I´m stuck, I have no idea how to modify the plugin, to get the result I want, so ANY HELP is appreciated (much!).

Hash: b3b0e810942ea22a36bd
Version: webpack 2.0.6-beta
Time: 307ms
Asset Size Chunks Chunk Names
0.js 985 bytes 0 [emitted]
2.js 977 bytes 2 [emitted]
3.js 1.93 kB 3 [emitted]
main.js 8.43 kB 4 [emitted] main
de_DE.js 2.86 kB 5, 2, 3 [emitted] de_DE
1.js 969 bytes 1 [emitted]
about.html 428 bytes [emitted]
index.html 422 bytes [emitted]
[5] ./src/i18n async ^\.\/.*\/app\.po$ 160 bytes {4} [built]
[6] ./src/i18n async ^\.\/.*\/plugin\.po$ 160 bytes {4} [built]
[7] multi main 28 bytes {4} [built]
+ 5 hidden modules
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment