学习如何写一个npm包

之前很好奇怎么上传一个包到npm,需要怎么样的项目结构,而最近做项目时,有考虑过用npm包的形式去开发,但发现只是自己的盲区,此文用于记录一下写npm包的过程。

这个包是用一个示例,主要判断用户登录状态,暂且命名为:login-test。

下面开始我们的npm包的制作过程

  1. 初始化一个项目

    mkdir login-test
    cd login-test
    npm init
    
  2. 添加我们的代码
    新建index.js文件。判断用户是否登录了

    module.exports = function(options) {
        const options = options || {};
        const sessionUser = options["sessionUser"] || "user";
        const redirect = options["redirect"] || "/login";
        return function(req,res,next) {
            if(!req.session[sessionUser]) {
                return res.redirect(redirect);
            }
            next();
        }
    }
    

    代码比较简单,sessionUser为空时则没有登录,跳转到/login(登录界面)

  3. 完善package.json文件
    个性化配置

    name:包的名字,确保该名字是独一无二的
    version:包的版本,默认是1.0.0
    description:包的描述
    main:入口文件,默认是index.js
    test command:测试命令
    repository:git仓库地址,一般为”type”:”git”,”url”:”git的url”
    keyword:这个挺重要,尽量用比较贴切的关键字作为这个包的索引,这样才能有更多的人搜索到你的包
    author:写你的账号或者你的github账号吧
    license:开源协议用了哪个

  4. 添加LICENCE文件,说明对应的开源协议

    我们新建一个名为 LICENSE 的文件,并在里面粘贴进如下内容

    The MIT License (MIT)
    
    Copyright (c) <year> <copyright holders>
    
    Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
    
    The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
    
    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
    
    

    <year><copyright holders>修改为 对应的年份 和 版权拥有者名字

  5. 添加 README.md 文件 和 .gitignore
    README.md 文件主要用于 该项目的一些说明,使用方法等
    在一些npm包中的README.md中,会看到类似于下图好看的版本信息
    在这里插入图片描述

    这些版本信息图标可以在 https://shields.io 制作
    在这里插入图片描述

  6. 发布npm包

    1.注册一个账号 https://www.npmjs.com

    2.在项目中,终端输入 npm adduser,然后按照提示输入。登录成功验证为:终端输入npm whoami,如果出现你的名字。

    3.发布npm包 npm publish --access=public

    4.在你的电脑上,直接npm install 你的包名,也可以在https://www.npmjs.com这里查找你发布的包。

猜你喜欢

转载自blog.csdn.net/vipshop_fin_dev/article/details/108980408