How to create and publish typescript package
--
I have recently created a package with typescript and publish it to npm. I wanted to document steps and help others who looking way to start.
Project setup
First, install typescript. After that, you will be able to use the Typescript compiler known as tsc.
#install typescript
npm install typescript --save-dev
Also add tsc script to package json.
"scripts": {
...
"tsc": "tsc"
},
Then initialize tsconfig. There will be some default options and commented options. This configuration sets how the Typescript compiler works. For example target option sets which ECMAScript version your code compiled into and the module option sets the import/export statements etc.
# initialize tscofig file
npm run tsc -- --init
For the starter below config works well. Target will be ES2015 which most modern platforms supports.
{
"compilerOptions": {
"target": "ES2015",
"module": "CommonJS",
"strict": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"outDir": "./lib",
"declaration": true,
"moduleResolution": "node",
"resolveJsonModule": true,
},
"include": [
"./src"
],
"exclude": [
"./node_modules",
"./lib"
]
}
More about these configurations can be found in official typescript docs.
Write logic
Let’s create a function that contains simple logic. This function accepts a string input, converts vowels to upper, others to lower case.
Only a “string” annotation is used but it still needs to be compiled into JS code for running it. Compile it with npm run tsc
. The compilation result will be like below.
- index.js compiled equivalent of index.ts file, all logical operations will be in it.
- index.d.ts is for type declartion, this behavior controlled with
"declartion":true
option in tsconfig.
Testing the Code
It’s good habit to write unit tests. Let’s setup test environment and write few lines to test.
#install jest
npm install jest ts-jest @types/jest --save-dev#also initialize jest config
npx ts-jest config:init
Jest comes with an internal coverage tool, while adding test command I also added coverage command.
"scripts": {
...
"tsc": "tsc"`,
"test": "jest",
"coverage": "jest --coverage"
},
Let’s write some test cases.
Check test results with npm test
command.
Versioning and publishing
NPM cli already has commands for versioning and publishing. I also created a GitHub Actions workflow to automate the process. This workflow below will be triggered on a commit pushed to the master branch.
- Before the version command, I have added some git commands to set user name and email. In this way, the version command can create a commit with that name and email.
- Npm access token can be created at npm website. Then I added my token to repository as github secret.
- Then lastly, pushed commit and tag which npm version command created.
Conclusion
In this article, I covered how to set up Typescript project, run tests and publish. Thanks for reading, have a nice day.
Resources: