Simple demonstration of packaging for UMD and ES modules using single project.
This project attempts to use one source code to distribute multiple packages. This project is compiled for UMD and ES modules. For more detail check the github repo.
Before anything we should install the dependencies:
npm i dj-hello-world
Write a html file importing the script.
<!-- you can import from node_modules -->
<script src="node_modules/dj-hello-world/index.js"></script>
<!-- or import from unpkg -->
<script src="https://unpkg.com/dj-hello-world@0.0.16/index.js"></script>
After importing the script you can use the global variable DJ_Hello_World
.
<script>
let world = new DJ_Hello_World.World();
world.sayHello();
</script>
Check the printed messages in the console from browser's Developer Tools tab.
Add the following script as type="module"
in a html file.
import { World, Language } from "/node_modules/dj-hello-world/index.esm.js";
const newWorld = new World();
newWorld.sayHello();
newWorld.setLanguage(Language.Chinese);
newWorld.sayHello();
Check the printed messages in the console from browser's Developer Tools tab.
Node.js uses CommonJS for managing packages. Meaning it uses the require
function to import the packages. Run the following script in node.js.
const djHelloWorld = require("dj-hello-world");
const helloWorld = djHelloWorld.helloWorld;
const World = djHelloWorld.World;
const Language = djHelloWorld.Language;
const newWorld = new World();
newWorld.sayHello();
newWorld.setLanguage(Language.Chinese);
newWorld.sayHello();
Check the printed messages in the console.