5

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.

1 Answer 1

4

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")
      ],
    }),
  ],
};

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.