/javascript-library-template

A Javascript library template project UMD (CommonJS, AMD, global variable) ready.

Primary LanguageJavaScriptMIT LicenseMIT

javascript-library-template

A Javascript library template project UMD (CommonJS, AMD, global variable) ready.

Gettig started

  • Clone this repo;

  • copy cloned content to your project's root folder;

  • in package.json, change the value of:

    • main property to your library distributable file name. Should be equal to webpack.config.js' output.filename property (more below);
    • module property to your project entry source file.
  • in webpack.config.js:

Examples

Lib side

Considering a package.json with properties:

{
    ...
    "main": "dist/example-lib.js",
    "module": "src/main.js"
}

A webpack.config.js with properties:

    ...
    output: {
        ...
        library: "exampleLib",
        filename: "example-lib.js"
    }

And a source code written like this:

export {fnOne, fnTwo} ;

function fnOne() {
    return "fnOne";
}

function fnTwo() {
    return "fnTwo";
}

Client side

It would be possible to import it via script tag:

<html>
<head>
...
</head>
<body>
...
<script src="example-lib.js"></script>
</body>
</html>
// script tag import generates a global object property
// the property exampleLib comes from webpack.config.js' output.library property
exampleLib.fnTwo();

It would also be possible to import it via CommonJs:

npm i --save library-name
//the name "example-lib" comes from webpack.config.js' output.filename property
const exampleLib = require("example-lib");
exampleLib.fnOne();
exampleLib.fnTwo();

And, finally, as an AMD module:

//the name "example-lib" comes also from webpack.config.js' output.filename property
requirejs(["example-lib.js"], function(exampleLib) {
    exampleLib.fnOne();
    exampleLib.fnTwo();
});

License

MIT