Skip to content

Commit

Permalink
New: Add first proof of concept
Browse files Browse the repository at this point in the history
  • Loading branch information
morriq committed Dec 8, 2018
0 parents commit a2eac54
Show file tree
Hide file tree
Showing 8 changed files with 4,116 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/.idea/
1 change: 1 addition & 0 deletions examples/umd/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/dist/
Empty file added examples/umd/d.js
Empty file.
1 change: 1 addition & 0 deletions examples/umd/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
const react = require('react')
18 changes: 18 additions & 0 deletions examples/umd/webpack.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
const { resolve } = require('path')
const MicroservicesWebpackPlugin = require('../../index.js')

module.exports = {
entry: resolve(__dirname, 'index.js'),
externals: {
react: 'react'
},
output: {
path: resolve(__dirname, 'dist'),
libraryTarget: 'amd'
},
plugins: [
new MicroservicesWebpackPlugin([
{ name: 'react', path: `umd/react.production.min.js` },
])
]
}
64 changes: 64 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
const { join } = require('path');
const { RawSource } = require('webpack-sources');

class MicroservicesWebpackPlugin {
constructor(
modules
) {
this.modules = modules || [];
this.url = 'https://unpkg.com/:name@:version/:path';
this.paramsRegex = /:([a-z]+)/gi;
this.node_modules = join(process.cwd(), 'node_modules');

this.modules = this.modules
.map(({ name, ...other }) => ({
name,
...other,
version: require(join(this.node_modules, name, 'package.json')).version
}))
.map(({ name, version, path }) => {
if (!path.includes('.js')) {
throw new Error(`Unsupported extension in ${path}`);
}

const cdn = this.url.replace(this.paramsRegex, (_, type) => ({
name,
version,
path
})[type]);

return {
name,
cdn
}
})
}

apply(compiler) {
compiler.hooks.emit.tapAsync(MicroservicesWebpackPlugin.name, this.tapAsync.bind(this))
}

tapAsync(compilation, callback) {
compilation.assets = Object.keys(compilation.assets)
.map((fileName) => {
if (!fileName.includes('.js')) {
throw new Error(`Unsupported extension in ${path}`);
}

const value = [
this.modules
.map(({ cdn, name }) => `define('${name}', ['${cdn}'], v => v)`)
.join('\n'),
compilation.assets[fileName].source()
].join('\n');

return {[fileName]: new RawSource(value)};
})
.reduce((previous, current) => ({ ...previous, ...current }), {});

callback()
}
}

// @todo add to externals, remove from chunk
module.exports = MicroservicesWebpackPlugin;
Loading

0 comments on commit a2eac54

Please sign in to comment.