refactor some webpack stuff, support service worker generation

This commit is contained in:
Rich Harris
2017-12-14 15:38:41 -05:00
parent 6e769496ec
commit b8c03d330b
2 changed files with 47 additions and 27 deletions

View File

@@ -1,8 +1,9 @@
const fs = require('fs');
const path = require('path');
const glob = require('glob');
const webpack = require('webpack');
module.exports = function create_webpack_compiler(out, routes, dev) {
module.exports = function create_webpack_compiler(dest, routes, dev) {
const compiler = {};
const client = webpack(
@@ -28,34 +29,52 @@ module.exports = function create_webpack_compiler(out, routes, dev) {
// TODO server
} else {
compiler.client_main = new Promise((fulfil, reject) => {
client.run((err, stats) => {
console.log(stats.toString({ colors: true }));
compiler.ready = Promise.all([
new Promise((fulfil, reject) => {
client.run((err, stats) => {
console.log(stats.toString({ colors: true }));
if (err || stats.hasErrors()) {
reject(err || stats.toJson().errors[0]);
}
const info = stats.toJson();
const filename = stats.toJson().assetsByChunkName.main;
fulfil(`/client/${filename}`);
});
});
if (err || stats.hasErrors()) {
reject(err || info.errors[0]);
}
const chunks = new Promise((fulfil, reject) => {
server.run((err, stats) => {
console.log(stats.toString({ colors: true }));
compiler.client_main = `/client/${info.assetsByChunkName.main}`;
compiler.assets = info.assets.map(asset => `/client/${asset.name}`);
if (err || stats.hasErrors()) {
reject(err || stats.toJson().errors[0]);
}
fulfil();
});
}),
fulfil(stats.toJson().assetsByChunkName);
});
new Promise((fulfil, reject) => {
server.run((err, stats) => {
console.log(stats.toString({ colors: true }));
const info = stats.toJson();
if (err || stats.hasErrors()) {
reject(err || info.errors[0]);
}
compiler.chunks = info.assetsByChunkName;
fulfil();
});
})
]).then(() => {
const assets = glob.sync('**', { cwd: 'assets' });
const service_worker = fs.readFileSync('templates/service-worker.js', 'utf-8')
.replace('__timestamp__', Date.now())
.replace('__assets__', JSON.stringify(assets))
.replace('__javascript__', JSON.stringify(compiler.assets));
fs.writeFileSync(path.resolve(dest, 'service-worker.js'), service_worker);
});
compiler.get_chunk = async id => {
const assetsByChunkName = await chunks;
return path.resolve(out, 'server', assetsByChunkName[id]);
return path.resolve(dest, 'server', compiler.chunks[id]);
};
}