Como construir e publicar um pacote Typescript para NPM

30 de agosto de 2021 0 Por sudoroot

Etapa 1: pacote init

1
2
mkdir name-typescript-package && cd name-typescript-package
npm init -y

Exemplo:

1
2
mkdir express-ip && cd express-ip
npm init -y

Resultado:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
D:\AppServ\www\node3>mkdir express-ip && cd express-ip
 
D:\AppServ\www\node3\express-ip>npm init -y
Wrote to D:\AppServ\www\node3\express-ip\package.json:
 
{
  "name": "express-ip",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

Etapa 2: instalar o typescript

1
npm i --save-dev typescript

Resultado:

1
2
3
4
5
6
7
8
9
D:\AppServ\www\node3\express-ip>npm i --save-dev typescript
npm notice created a lockfile as package-lock.json. You should commit this file.
 
npm WARN [email protected] No description
npm WARN [email protected] No repository field.
 
added 1 package from 1 contributor and audited 1 package in 7.943s
found 0 vulnerabilities

Etapa 3: configuração do texto tipográfico:

1
npx tsc --init

Resultado:

1
2
D:\AppServ\www\node3\express-ip>npx tsc --init
message TS6071: Successfully created a tsconfig.json file.

Etapa 4: editar o arquivotsconfig.json

1
2
3
4
5
6
7
8
9
10
11
{
  "compilerOptions": {
    "target": "es2015"      /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */,
    "module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */,
    "declaration": true  /* Generates corresponding '.d.ts' file. */,
    "outDir": "./lib"    /* Redirect output structure to the directory. */,
    "strict": true       /* Enable all strict type-checking options. */
  },
  "include": ["src"],    /* Typescript source code */
  "exclude": ["node_modules", "test"]
}

Etapa 5: escreva seus próprios códigos
Exemplo: crie o arquivo./src/index.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import * as geoip from 'geoip-country'
 
export function getIpInfo (ip:string) {        
    var lookedUpIP = geoip.lookup(ip);
 
    if (!lookedUpIP){
        return { error: "Error occured while trying to process the information" }
    }
    return lookedUpIP;
}
 
export function getIpInfoMiddleware (opts={DEVIP:'1.1.1.1'}){
    return function (req:any, res:any, next:any) {
        var xForwardedFor = (req.headers['x-forwarded-for'] || '').replace(/:\d+$/, '');
        var cfConnectingIp = req.headers['cf-connecting-ip'] || '';
        var incapClientIp = req.headers['incap-client-ip'] || '';
        var xSucuriClientIp = req.headers['x-sucuri-clientip'] || '';
        var ip = cfConnectingIp || incapClientIp || xSucuriClientIp || xForwardedFor           
        ip = (ip && ip.split(",").shift()) || req.connection.remoteAddress;
        if (ip.includes('::ffff:')) {
            ip = ip.split(':').reverse()[0]
        }  
        if ((ip === '127.0.0.1' || ip === '::1')) {
            ip = opts.DEVIP || '1.1.1.1'
        }
        req.ipInfo = { ip, ...getIpInfo(ip) };
        next();
    }
}

Etapa 6: editar o arquivopackage.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
{
  "name": "@sansamour/express-ip",
  "version": "1.0.0",
  "description": "",
  "main": "lib/index.js",
  "types": "lib/index.d.ts",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "prepare" : "npm run build",
    "build": "tsc" 
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "typescript": "^4.4.2" 
  },
  "files": [
    "lib"
  ]
}

Etapa 7: instale dependências:
Exemplo: npm i geoip-country

1
2
3
4
5
6
7
8
9
10
11
D:\AppServ\www\node3\express-ip>npm i geoip-country
npm WARN @sansamour/[email protected] No description
npm WARN @sansamour/[email protected] No repository field.
 
added 31 packages from 23 contributors and audited 32 packages in 9.256s
 
1 package is looking for funding
  run `npm fund` for details
 
found 0 vulnerabilities
1
npm i --save-dev @types/geoip-country
1
2
3
4
5
6
7
8
9
10
11
D:\AppServ\www\node3\express-ip>npm i --save-dev @types/geoip-country
npm WARN @sansamour/[email protected] No description
npm WARN @sansamour/[email protected] No repository field.
 
added 1 package from 1 contributor and audited 33 packages in 2.882s
 
1 package is looking for funding
  run `npm fund` for details
 
found 0 vulnerabilities

Etapa 8: construir

1
2
3
4
D:\AppServ\www\node3\express-ip>npm run build
 
> @sansamour/[email protected] build D:\AppServ\www\node3\express-ip
> tsc

Etapa 9: teste seu pacote:

Criar arquivo test / test.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const request = require('supertest');
const express = require('express');
const {getIpInfoMiddleware} = require('../lib/index');
 
const app = express();
app.use(getIpInfoMiddleware());
 
app.get('/ipInfo', function(req, res) {
  res.status(200).json(req.ipInfo);
});
 
request(app)
  .get('/ipInfo')
  .expect('Content-Type', /json/)
  .expect(200)
  .end(function(err, res) {
    if (err) throw err;
    console.log(res.body);
  });

Editar arquivo package.json

1
"test": "node test/test.js",

Instale dependências:

1
2
npm install supertest --save-dev
npm install express --save-dev

Corre:

1
2
3
4
5
6
D:\AppServ\www\node3\express-ip>npm run test
 
> @sansamour/[email protected] test D:\AppServ\www\node3\express-ip
> node test/test.js
 
{ ip: '1.1.1.1', range: [ 16843008, 16843263 ], country: 'AU' }

Etapa 9.2 (opção): criar arquivo.npmignore

1
2
3
4
5
/ignore
/.gitignore
/node_modules
/.npmignore
/.git

Etapa 10: publicar no NPM

Login npm: npm login

Resultado:

1
2
3
4
5
D:\AppServ\www\node3\express-ip>npm login
Username: sansamour
Password:
Email: (this IS public) [email protected]
Logged in as sansamour on https://registry.npmjs.org/.

login npm

Publicar: npm publish --scope sansamour --access public

Resultado:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
D:\AppServ\www\node3\express-ip>npm publish --scope sansamour --access public
 
> @sansamour/[email protected] prepare .
> npm run build
 
 
> @sansamour/[email protected] build D:\AppServ\www\node3\express-ip
> tsc
 
npm notice
npm notice package: @sansamour/[email protected]
npm notice === Tarball Contents ===
npm notice 1.3kB lib/index.js
npm notice 524B  package.json
npm notice 262B  lib/index.d.ts
npm notice === Tarball Details ===
npm notice name:          @sansamour/express-ip
npm notice version:       1.0.0
npm notice package size:  1.1 kB
npm notice unpacked size: 2.1 kB
npm notice shasum:        f98e27f08cfbaf9d14da2ba4597ec36e929d39be
npm notice integrity:     sha512-JhEx6ghh+ije0[...]cchiymrRsC0Ew==
npm notice total files:   3
npm notice
+ @sansamour/[email protected]

npm publicar