Skip to content

Instantly share code, notes, and snippets.

@ken-okabe
Last active August 10, 2018 12: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 ken-okabe/2a1ce1485899ffa00fbff181cf5f98d8 to your computer and use it in GitHub Desktop.
Save ken-okabe/2a1ce1485899ffa00fbff181cf5f98d8 to your computer and use it in GitHub Desktop.
{
//Issue:
//not compatible with TypeScript Types
// "@types/react"
// "@types/react-dom"
//TypeScript
// import * as React from "react";
// import * as ReactDOM from "react-dom";
//This ESMs
// import React from "react"
// import ReactDOM from "react-dom"
// This is problematic on TypeScript>JavaScript
const rollup = require('rollup');
const commonjs = require('rollup-plugin-commonjs');
const nodeResolve = require('rollup-plugin-node-resolve');
const json = require('rollup-plugin-json');
const fs = require('fs');
const builtins = require('rollup-plugin-node-builtins');
const globals = require('rollup-plugin-node-globals');
const plugins = () => {
return [
json(),
commonjs({
sourceMap: false,
namedExports: {
'node_modules/process/browser.js': ['nextTick'],
'node_modules/events/events.js': ['EventEmitter'],
'node_modules/buffer/index.js': ['isBuffer']
}
}),
nodeResolve({
jsnext: true,
main: true,
preferBuiltins: false,
browser: true
}),
globals(),
builtins()
];
};
class cjsModule {
constructor(name, path, getPlugins) {
this.name = name
this.path = path
this.cjsLocalPath = `${this.path}${this.name}.min.js`
this.cjsPath = `${this.path}${this.name}.js`
this.fromNpm = !fs.existsSync(this.cjsLocalPath)
this.inputOptions = {
input: this.fromNpm ? this.cjsPath : this.cjsLocalPath,
plugins: getPlugins()
}
this.outputOptions = {
file: `${this.path}${this.name}-esm.js`,
format: 'es'
}
}
async toES6() {
let _bundle = async () => {
const bundle = await rollup.rollup(this.inputOptions);
await bundle.write(this.outputOptions);
}
if (this.fromNpm) {
fs.writeFile(this.cjsPath, `import * as NodeModule from '${this.name}'; export default NodeModule.default;`, async () => {
await _bundle()
fs.unlink(this.cjsPath, () => { })
});
} else {
await _bundle()
}
}
}
//For instace
const path = "./esm/"
const modules = ["react", "react-dom"]
modules.forEach(module => new cjsModule(module, path, plugins).toES6());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment