Skip to content

Instantly share code, notes, and snippets.

@anandthakker
Last active November 13, 2018 16:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anandthakker/ae7955882d7d9f300eaf9bd894742ef9 to your computer and use it in GitHub Desktop.
Save anandthakker/ae7955882d7d9f300eaf9bd894742ef9 to your computer and use it in GitHub Desktop.
// Used by the second rollup pass to reassemble the code-split chunks into a single bundle.
import './out/chunk1.js';
import './out/worker.js';
import './out/main.js';
export default lib;
<script src="out/final_bundle.js"></script>
<script>
myLib.start();
</script>
import util from './util';
let workerUrl;
export default {
start: function () {
const worker = new Worker(this._workerUrl)
worker.addEventListener('message', (message) => {
console.log(message.data);
});
util.send(worker, 'start');
},
_workerUrl: null // set at runtime when bundle is executed
}
export default [{
input: ['./worker.js', './main.js'],
output: {
dir: 'out',
format: 'amd',
},
experimentalCodeSplitting: true
}, {
input: './bundle.js',
output: {
name: 'myLib',
file: 'out/final_bundle.js',
format: 'umd'
},
intro: `
// Hijack "define" so we can store the factory functions for the shared and
// worker AMD "chunks" created in the code-splitting build pass.
// Very hacky, deeply coupled with the code in bundle.js
let shared, worker;
let lib; // delcare 'lib' -- which is exported by bundle.js -- so we can set its value here
function define(_, module) {
if (!shared) {
shared = module;
} else if (!worker) {
worker = module;
} else {
// execute the shared chunk
const sharedChunk = {};
shared(sharedChunk);
// execute the main chunk
lib = module(sharedChunk);
// create a string of code that's analogous to the above, but for the worker.
const workerBundleString = 'const sharedChunk = {}; (' + shared + ')(sharedChunk); (' + worker + ')(sharedChunk);'
// Create a blob URL from this code string, save it on 'lib' to be used
// when creating web workers
lib._workerUrl = window.URL.createObjectURL(new Blob([workerBundleString], { type: 'text/javascript' }));
}
}
`
}];
export default {
description: `Shared by both the main thread script and the web worker`,
send: (target, data) => {
target.postMessage(data);
}
}
import util from './util';
self.onmessage = () => {
util.send(self, 'started');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment