mkdir get-px
npm init
以後填寫main入口的時候注意下,寫成./dist/get-px.jsnode
{ "name": "get-px", "version": "1.0.0", "description": "a demo of ts", "main": "./dist/get-px.js", "scripts": { "test": "echo \\"Error: no test specified\\" && exit 1" }, "keywords": [ "typescript" ], "author": "jjyin", "license": "MIT" }
tsc --init
獲得一個帶註釋的tsconfig.json文件。typescript
接着關閉compilerOptions對象的如下注釋,並設置。npm
"declaration": true, /\* Generates corresponding '.d.ts' file. \*/ // ... // 設置爲./dist "outDir": "./dist", /\* Redirect output structure to the directory. \*/ // ...
添加一個exclude。json
"exclude": [ "./dist", "./example" ]
npm i typescript -D
touch get-px.ts
// get-px.ts const getPX = (arg: string | number): string => { if (typeof arg === 'string') { if (arg.substring(arg.length - 2) === 'px') { return arg; } else { throw new Error('the argument of getPX should be a string width \\'px\\''); } } else { return arg + 'px' } } export = getPX;
tsc
以後,dist文件生成測試
驗證一下生成的get-px.js文件。ui
把get-px.js文件看成是一個庫文件引入使用驗證一下是否可行。this
一、新建一個測試文件,在dist文件夾同級,新建一個example文件夾,裏面新建test.ts文件,以下所示。spa
// test.ts import getPX = require('./../dist/get-px'); console.log(getPX(1));
二、編譯test.ts文件code
cd example tsc test.ts
三、查看生成的test.js文件對象
四、node運行一下test.js文件
可行。
npm login
若是在npm官網沒註冊過帳號,先註冊一下,再登陸。
輸入用戶名、密碼、郵箱。
若是登陸遇到npm ERR! no_perms Private mode enable, only admin can publish this module:這個錯誤,能夠嘗試以下解決方法。
npm config set registry http://registry.npmjs.org
/example/
把不須要發佈的文件寫在裏面。
// 回到上一級目錄 cd .. // 發佈 npm publish
發佈成功
爲防止有衝突,在安裝使用get-px以前,先改一下package.json文件的name屬性。
npm i get-px@1.0.0
test.ts文件中的引入文件,改寫成
import getPX = require('get-px'); console.log(getPX(1));
控制檯執行
cd example tsc test.ts node test.js
結果