Skip to content

Instantly share code, notes, and snippets.

@mzgoddard
Created November 16, 2016 19:34
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mzgoddard/f6dbbe49bc5e05e7d6ddd15fa1beb0df to your computer and use it in GitHub Desktop.
Save mzgoddard/f6dbbe49bc5e05e7d6ddd15fa1beb0df to your computer and use it in GitHub Desktop.
Plugin brainstorm to support async attribute use on script tags with webpack.
function ScriptAsyncAttrSupportPlugin() {}
module.exports = ScriptAsyncAttrSupportPlugin;
ScriptAsyncAttrSupportPlugin.prototype.apply = function(compiler) {
compiler.plugin('this-compilation', function(compilation) {
compilation.mainTemplate.plugin('bootstrap', function(source) {
return this.asString([
source,
'',
'if (window["__webpackJsonp"]) {',
' var chunks = __webpackJsonp.slice();',
' Promise.resolve()',
' .then(function() {',
' chunks.forEach(function(chunkCb) {',
' chunkCb();',
' });',
' });',
'}',
]);
});
});
// Need to connect this plugin after JsonpChunkTemplatePlugin. The order of
// the main template piece doesn't really matter.
compiler.plugin('after-plugins', function() {
compiler.plugin('this-compilation', function(compilation) {
compilation.chunkTemplate.plugin('render', function(source) {
return this.asString([
'if (!window["webpackJsonp"]) {',
' window["webpackJsonp"] = function(args) {',
' args = [].slice.call(arguments);',
' if (!window["__webpackJsonp"]) {',
' window["__webpackJsonp"] = [];',
' }',
' window["__webpackJsonp"].push(function() {',
' webpackJsonp.apply(null, args);',
' });',
' delete window["webpackJsonp"];',
' };',
'}',
'',
source.source(),
]);
});
});
});
};
var webpack = require('webpack');
module.exports = {
context: __dirname,
entry: {
vendor: ['react', 'react-dom'],
main: './index',
},
output: {
path: 'dist',
filename: '[name].js',
},
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production'),
}),
new webpack.optimize.UglifyJsPlugin(),
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
}),
new (require('./script-async-attr-support-plugin'))(),
],
}
var h = require('react').createElement;
var render = require('react-dom').render;
function Root() {
return h('div', null, 'hello world');
}
render(h(Root), document.querySelector('#root'));
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="root"></div>
<script async src="dist/vendor.js"></script>
<script async src="dist/main.js"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment