npm 包开发

Fork Me On Github

准备

nodejs

vscode

流程

注册npm账号

新建文件夹 test

vscode 中打开

ctrl + ` 打开 cmd 模式下登录

  
npm login
12

输入账号密码

输入 npm init

输入项目名及说明生成 package.json 文件

  
npm i @types/node gulp gulp-typescript typescript --save-dev
12

新建文件夹 src

src 下添加 index.ts

根目录添加 gulpfile.js

输入内容

js
          
var gulp = require('gulp'),
    ts = require("gulp-typescript"),
    tsProject = ts.createProject('tsconfig.json');

gulp.task('default', async() => {
    await gulp.src('src/**/*.ts')
        .pipe(tsProject())
        .pipe(gulp.dest('dist/'));
});
12345678910

根目录添加 tsconfig.json

json
                 
{
  "compilerOptions": {
    "baseUrl": "./",
    "declaration": true,
    "typeRoots": [
      "./node_modules/@types"
    ]
  },
  "include": [
    "src/**/*.ts"
  ],
  "exclude": [
    "node_modules",
    "dist",
    "**/*.spec.ts"
  ]
}
1234567891011121314151617

修改 package.json

json
 
"main": "dist/index.js",
1

将入口指向编译生成的 index.js 文件

添加

json
   
"files": [
    "dist"
],
123

只需要 dist 文件夹下的文件就行了,其他源码就不用发布了

src/index.ts

ts
        

function test() {
    console.log('test');
}

export default test;

module.exports = test;
12345678

执行 gulp 命令

dist 下会自动生成 index.jsindex.d.ts 两文件

  
npm publish
12

发布成功

在其他项目

  
npm i test
12

安装此包

使用

ts
 
import test from 'test';
1

js
 
var test = require('test);
1

添加 bin

添加 bin 文件夹

新建文件 cli.js(文件名随意)

js
   
#!/usr/bin/env node

console.log(1);
123

然后在 package.json 配置

json
   
"bin": {
  "command-name": "./bin/cli.js"  //告诉package.json,我的bin叫 command-name ,它可执行的文件路径是bin/cli.js
}
123

bin 命令必须全局安装才能用

 
npm install . -g
1

 
npm link
1
点击查看全文
0 507 0