Created
May 20, 2018 19:43
-
-
Save bard/5cb927e7abb6988b2f2e516b5f0e6070 to your computer and use it in GitHub Desktop.
ParcelJS - hack to post-process entire bundles
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"dependencies": { | |
"es3ify": "^0.2.2", | |
"parcel-bundler": "^1.8.1" | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require('fs') | |
const util = require('util') | |
const writeFileAsync = util.promisify(fs.writeFile) | |
const Bundler = require('parcel-bundler') | |
const es3ify = require('es3ify') | |
const JSPackager = parseInt(process.versions.node, 10) < 8 | |
? require('parcel-bundler/lib/packagers/JSPackager') | |
: require('parcel-bundler/src/packagers/JSPackager') | |
class ES3ifyingJSPackager extends JSPackager { | |
async setup () { | |
const result = await super.setup() | |
// Throw away `this.dest` (a writestream) from superclass and | |
// replace it with a mock stream that buffers input and transforms | |
// it to ES3 just before writing it to disk. | |
this.dest = { | |
_buffer: [], | |
path: this.dest.path, | |
async write (data) { | |
this._buffer += data | |
}, | |
async end () { | |
const transformed = es3ify.transform(this._buffer) | |
return writeFileAsync(this.path, transformed) | |
} | |
} | |
return result | |
} | |
} | |
const bundler = new Bundler('./src/index.html', { | |
outDir: './dist', | |
outFile: 'index.html' | |
}) | |
bundler.addPackager('js', ES3ifyingJSPackager) | |
bundler.bundle() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Parcel allows to transform individual assets, e.g. js sources with Babel, html sources with PostHTML, etc. but sometimes one wants to transform the resulting bundle (sources + whatever code Parcel is wrapping them in).
In my case I needed an ES3-compliant code base and just transforming my sources resulted in ES3-compliant code wrapped in non-ES3 compliant wrappers. This hack allowed me to ES3ify the entire bundle. Another possible use would be to inline scripts and stylesheets.
Warning: will most likely mess with source maps.