npm 包开发

Fork Me On Github

准备

nodejs

vscode

流程

注册npm账号

新建文件夹 test

vscode 中打开

ctrl + ` 打开 cmd 模式下登录

npm login

输入账号密码

输入 npm init

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

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

新建文件夹 src

src 下添加 index.ts

根目录添加 gulpfile.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/'));
});

根目录添加 tsconfig.json

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

修改 package.json

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

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

添加

"files": [
    "dist"
],

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

src/index.ts


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

export default test;

module.exports = test;

执行 gulp 命令

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

npm publish

发布成功

在其他项目

npm i test

安装此包

使用

import test from 'test';

var test = require('test);

添加 bin

添加 bin 文件夹

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

#!/usr/bin/env node

console.log(1);

然后在 package.json 配置

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

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

npm install . -g

npm link
Click here to view
0 451 0