模擬封裝一個含ts聲明文件的js庫併發布npm包

新建一個文件夾

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初始化

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"

]

安裝typescript

npm i typescript -D

新建主代碼文件——get-px.ts

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;

編譯文件get-px.ts

tsc

以後,dist文件生成
image.png測試

驗證一下生成的get-px.js文件。
image.pngui

把get-px.js文件看成是一個庫文件引入使用驗證一下是否可行。this

一、新建一個測試文件,在dist文件夾同級,新建一個example文件夾,裏面新建test.ts文件,以下所示。
image.pngspa

// test.ts
import getPX = require('./../dist/get-px');

console.log(getPX(1));

二、編譯test.ts文件code

cd example
 
 tsc test.ts

三、查看生成的test.js文件
image.png對象

四、node運行一下test.js文件
image.png

可行。

發佈npm包

登陸

npm login

若是在npm官網沒註冊過帳號,先註冊一下,再登陸。

輸入用戶名、密碼、郵箱。

若是登陸遇到npm ERR! no_perms Private mode enable, only admin can publish this module:這個錯誤,能夠嘗試以下解決方法。

npm config set registry http://registry.npmjs.org

添加.npmignore文件

/example/

把不須要發佈的文件寫在裏面。

發佈

// 回到上一級目錄
cd ..

// 發佈
npm publish

發佈成功
image.png

使用發佈的包

爲防止有衝突,在安裝使用get-px以前,先改一下package.json文件的name屬性。
image.png

安裝

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

結果
image.png

相關文章
相關標籤/搜索