Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge ES6 class source files?

The goal is to create a bower compatible package.

I'm new to packaging, did some research but no clue yet.

The problem is simplified as below:

\src\ID.js
\src\Person.js

ID.js

export default class ID {
    static gen() {
        return 'a unique ID';
    }
}

Person.js

import ID from './ID.js';

export default class Person {
    constructor(name) {
        this.name = name;
        this.id   = ID.gen();
    }
}

The only class should be exposed is Person, ID will only be used internally.

If I want to create a package named person, then I would assume it's better to build all the source files into one.

I know a little bit of merging using ES5, but with ES6 classes, I have no idea.

Maybe I could create a parent object to hold these two classes? But I would really like to know the proper way. If no such way, I would also take something like compiling ES6 to ES5 methods.

like image 270
Madwyn Avatar asked Sep 27 '22 04:09

Madwyn


1 Answers

You can use rollup: https://github.com/rollup/rollup (I'm assuming you have nodejs installed)

$ npm install -g rollup

$ rollup --input src/Person.js --output dist/Person.js --format iife --name Person

This command generates this file:

var Person = (function () { 'use strict';

    class ID {
        static gen() {
            return 'a unique ID';
        }
    }

    class Person {
        constructor(name) {
            this.name = name;
            this.id   = ID.gen();
        }
    }

    return Person;

})();

The --format parameter can be

  • iife: rollup generates a function which saves the exported variable into a variable named as specified by the --name parameter
  • amd, if you use RequireJS or other AMD-compliant module managers
  • cjs, if you need to run your module in node.js
  • umd = iife + amd + cjs
  • es6 (default): rollup exports variables using es6 modules

If you need to run your code in browsers which don't support ES6, you can transpile it using babel:

$ npm install rollup-plugin-babel
$ npm install babel-preset-es2015-rollup

$ rollup --config config.js --input src/Person.js --output dist/Person.js

config.js:

var babel = require("rollup-babel-plugin");

module.exports = {
  format: "iife", // --format
  moduleName: "person", // --name
  plugins: [
    babel({
      presets: [
        require("babel-preset-es2015-rollup")
      ],
    }),
  ],
};
like image 64
Nicolò Avatar answered Oct 23 '22 00:10

Nicolò