esm-and-other-format-libraries-starter
This is a start kit for developing ECMAScript standard EM Modules format library with TypeScript.
Explanation of Build Files.
ES Module | UMD | CommonJS |
---|---|---|
your-library.esm.js | your-library.js | your-library.common.js |
Create your library.
In this chapter, we will explain how to implement libraries in three formats: ECMAScript standard, CommonJS, and UMD.
-
Create project.
mkdir your-library && cd $_; -
Create project configuration file.
Execute the following command.
This will create package.json at the root of the project.npm init -y;Open package.json and edit as follows.
..."main": "dist/your-library.common.js""module": "dist/your-library.esm.js""browser": "dist/your-library.js""types": "types/your-library.d.ts"...Name Value Description main dist/your-library.common.js Library name to output in CommonJS format. module dist/your-library.esm.js Library name to output in ES Modules format. browser dist/your-library.js Library name output in UMD format. types types/your-library.d.ts Set the typescript declaration file. -
Install required packages.
npm i -D \typescript \ts-node \tsconfig-paths \rollup \rollup-plugin-typescript2 \rollup-plugin-terser \jest \@types/jest \ts-jest;Name Description typescript Used to compile TypeScript source code into JavaScript. ts-node Used to execute TypeScript code on a node and immediately check the result. tsconfig-paths Used to resolve paths (alias) in tsconfig.json at runtime with ts-node. rollup Rollup is a module bundler.
Used to bundle ES Modules, CommonJS, and UMD libraries for distribution to clients.rollup-plugin-typescript2 Plug-in for processing typescript with rollup. rollup-plugin-terser Used to compress bundle files. jest Jest is a library for testing JavaScript code. @types/jest Jest's type declaration. ts-jest A TypeScript preprocessor required to test projects written in TypeScript using Jest. -
Create a TypeScript compilation configuration.
Create TypeScript compilation configuration file.
touch tsconfig.json;Add content:
"compilerOptions":"target": "ESNext""module": "ESNext""declarationDir": "./types""declaration": true"outDir": "./dist""rootDir": "./src""strict": true"noImplicitAny": true"baseUrl": "./""paths": "~/*": "src/*""esModuleInterop": true"include":"src/**/*""exclude":"node_modules""**/*.test.ts"Option Value Description compilerOptions target ESNext Specify ECMAScript target version.
"ESNext" targets latest supported ES proposed features.module ESNext Specify module code generation.
"ESNext" is an ECMAScript standard, and import/export in typescript is output as import/export.declarationDir ./types Output directory for generated declaration files. declaration true Generates corresponding .d.ts file. outDir ./dist Output directory for compiled files. rootDir ./src Specifies the root directory of input files. baseUrl ./ Base directory to resolve non-relative module names. paths {
"~/*": ["src/*"]
}List of path mapping entries for module names to locations relative to the baseUrl.
Set the alias of "/ src" directly under the root with "~ /".
e.g. import Awesome from '~/components/Awesome';include [
"src/**/*"
]A list of glob patterns that match the files to be included in the compilation.
Set the source directory.exclude [
"node_modules",
"**/*.test.ts"
]A list of files to exclude from compilation.
Set node_modules and unit test code. -
Create a library module with a type script.
Create a directory to store source files.
mkdir src;Submodule that calculates the subtraction.
// src/add.ts/*** Sum two values*/:number {return a + b;}Submodule that calculates the addition.
// src/sub.ts/*** Diff two values*/:number {return a - b;}Main module that imports multiple modules and exports a single library.
// src/your-library.ts;;; -
Let's run the library on node.
Run the following command.
To run on node, it is important to set the module option to CommonJS.npx ts-node -r tsconfig-paths/register -P tsconfig.json -O '{"module":"commonjs"}' -e "\import {add} from '~/your-library';console.log('1+2=' + add(1,2));";# 1+2=3 -
Setting up and running unit tests.
Create unit test configuration file.
touch jest.config.js;Add content:
const pathsToModuleNameMapper = ;const compilerOptions = ;moduleexports =roots:'<rootDir>/src''<rootDir>/tests/'transform:'^.+\\.tsx?$': 'ts-jest'testRegex: '(/tests/.*|(\\.|/)(test|spec))\\.tsx?$'moduleFileExtensions:'ts''js'moduleNameMapper:// moduleNameMapper: {// '^~/(.+)': '<rootDir>/src/$1'// }Name Description roots A list of paths to directories that Jest should use to search for files in.
Specify the directory path where the source code (./src) and test code (./tests) files are located.transform Instruct Jest to transpile TypeScript code with ts-jest. testRegex Specify the file and directory to be teste. moduleFileExtensions Specifies the extension of the file to be tested. moduleNameMapper Apply alias setting of actual path set in "baseUrl" and "paths" of tsconfig.json. Create a tests directory to store test code at the root of the project.
mkdir tests;Then, Create add.test.ts and sub.test.ts files in the tests directory.
This will contain our actual test.// tests/add.test.ts;;// tests/sub.test.ts;;Open your package.json and add the following script.
..."scripts":"test": "jest"...Run the test.
npm run test;Jest will print this message.
You just successfully wrote your first test.PASS tests/add.test.tsPASS tests/sub.test.tsTest Suites: 2 passed, 2 totalTests: 2 passed, 2 totalSnapshots: 0 totalTime: 1.332s, estimated 3sRan all test suites. -
Run the build.
There is one caveat.
Convert UMD library names in global namespace from snake case to camel case. In the case of e.g.your-library, it will be window.yourLibrary.Create a build configuration file.
touch rollup.config.js;Add content:
;;;external: Objectinput: './src/your-library.ts'plugins:output:// ES module (for bundlers) build.format: 'esm'file: pkgmodule// CommonJS (for Node) build.format: 'cjs'file: pkgmain// browser-friendly UMD buildformat: 'umd'file: pkgbrowsername: pkgbrowserName Description external Comma-separate list of module IDs to exclude. input The bundle's entry point(s) (e.g. your main.js or app.js or index.js). plugins Plugins allow you to customise Rollup's behaviour by, for example,
transpiling code before bundling, or finding third-party modules in your node_modules folder.
Use rollup-plugin-typescript2 and rollup-plugin-terser.
rollup-plugin-typescript2 is a TypeScript loader, and this plugin reads "tsconfig.json" by default.
rollup-plugin-terser compresses source code.output The output destination of the bundle.
Three types of libraries, ES Modules, CommonJS, and UMD, are output.Open your package.json and add the following script.
..."scripts":"build": "rollup -c"...Run the build.
npm run build;The library compilation result and declaration file are output to the project root.
You just built successfully.. -- dist/ -- your-library.esm.js -- your-library.common.js -- your-library.js -- types/ -- your-library.d.ts -- add.d.ts -- sub.d.ts
How to publish a npm package
-
Create an NPM user locally.
When the command is executed, a '~/.npmrc' file is created and the entered information is stored.npm set init.author.name 'Your name';npm set init.author.email 'your@email.com';npm set init.author.url 'https://your-url.com';npm set init.license 'MIT';npm set init.version '1.0.0'; -
Create a user on npm.
If the user is not registered yet, enter the new user information to be registered in npm.
If an npm user has already been created, enter the user information and log in.npm adduser; -
Create a repository on GitHub and clone.
git clone https://github.com/your-user/your-repository.git; -
Setting files to be excluded from publishing
Create an .npmignore file at the root of the project.
.npmignore
Add node_modules and package-lock.json to .npmignore not to publish.
node_modules/ package-lock.json
-
Create v1.0.0 tag on GitHub.
git tag -a v1.0.0 -m 'My first version v1.0.0';git push origin v1.0.0; -
Publish to npm
npm publish;
How to upgrade NPM packages
-
Push program changes to github
git commit -am 'Update something';git push; -
Increase version
npm version patch -m "Update something"; -
Create a new version tag on Github
git push --tags; -
Publish to npm
npm publish;
Try this library
-
Create project.
mkdir myapp && cd $_; -
Create project configuration file.
npm init -y; -
Install this library.
npm i -S esm-and-other-format-libraries-starter; -
Create HTML.
touch index.html; -
Try the library.
-
For ES Modules:
The ES Modules library can be run in the browser immediately without compiling.
Add the following code to myapp/index.html and check with your browser.
<script type="module">;console;// 1+2=3</script> -
For CommonJS:
The CommonJS library cannot be executed in the browser as it is, so it must be compiled into a format that can be executed in the browser.
Install webpack for build.
npm i -D webpack webpack-cli;Create a module that runs the library.
Prepare myapp/app.js and add the following code.;console;// 1+2=3Compile "myapp/app.js" into a format that can be executed by a browser.
The compilation result is output to "myapp/app.budle.js".npx webpack app.js -o bundle.js;Add the following code to myapp/index.html and check with your browser.
-
For UMD:
The UMD library can be executed globally. It's very easy, but I don't like it because it makes module dependencies unclear.
Add the following code to myapp/index.html and check with your browser.
-
Difference in tscofig module output results.
Check what JavaScript code is generated according to the setting value of module of tsconfig.
-
The following is a module written in TypeScript used in the experiment.
Main module.
// ./src/app.ts;const result = ;Sub module.
// ./src/add.ts:number {return a + b;} -
Experimental results
-
'target' is 'ESNext' and 'module' is 'es2015' or 'ESNext':
// ./dist/app.js;const result = ;// ./dist/add.js{return a + b;} -
'target' is 'ESNext' and 'module' is 'none' or 'commonjs':
// ./dist/app.js"use strict";var __importDefault = this && this__importDefault || {return mod && mod__esModule ? mod : "default": mod ;};Object;const add_1 = ;const result = add_1;// ./dist/add.js"use strict";Object;{return a + b;}exportsdefault = default_1; -
'target' is 'ESNext' and 'module' is 'amd':
/dist/appjsvar __importDefault = this && this__importDefault || {return mod && mod__esModule ? mod : "default": mod ;};;// ./dist/add.js; -
'target' is 'ESNext' and 'module' is 'system':
// ./dist/app.jsSystem;// ./dist/add.jsSystem; -
'target' is 'ESNext' and 'module' is 'umd':
// ./dist/app.jsvar __importDefault = this && this__importDefault || {return mod && mod__esModule ? mod : "default": mod ;};{if typeof module === "object" && typeof moduleexports === "object"var v = ;if v !== undefined moduleexports = v;else if typeof define === "function" && defineamd;} {"use strict";Object;const add_1 = ;const result = add_1;};// ./dist/add.js{if typeof module === "object" && typeof moduleexports === "object"var v = ;if v !== undefined moduleexports = v;else if typeof define === "function" && defineamd;} {"use strict";Object;{return a + b;}exportsdefault = default_1;};
-
Reference
License
Author
- Twitter: @TakuyaMotoshima
- Github: TakuyaMotoshima mail to: development.takuyamotoshima@gmail.com