A Javascript library template project UMD (CommonJS, AMD, global variable) ready.
-
Clone this repo;
-
copy cloned content to your project's root folder;
-
in package.json, change the value of:
-
in webpack.config.js:
- change the value of output.library to your library exported object name;
- change de value of output.filename to your library file name;
- add needed externals.
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";
}
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();
});