组件上传至npm包

操作:

  • 在项目中的任意位置新建一个文件夹并进入该文件夹

    mkdir zppsakura-npm-demo
    
  • 初始化一个 package.json

    npm init --yes (--yes 表明用默认的配置信息,可不加)
    
    {
      "name": "zppsakura-npm-demo",  // 包名
      "version": "1.0.0",  // 版本号
      "description": "",  // 包的说明
      "main": "index.js",  // 入口文件
      "scripts": { // 可执行的脚本命令
        "test": "echo "Error: no test specified" && exit 1"
      },
      "keywords": [], // 关键字
      "author": "", // 作者
      "license": "ISC" // 许可证书
    }
    
  • 安装依赖包

    npm install rimraf babel-cli babel-preset-es2015
    
  • 在项目目录下创建src文件夹和index.js文件

    • src 存放开发的代码源文件
    • index.js 为包入口
  • index.js中输入以下内容

    module.exports = require('./lib/hello.js')
    
  • 在src文件夹下创建hello.js文件,内容如下

    class Hello{
     
    	say(){
    		console.log('hello world!!');
    	}
    }
    
    export default Hello;
    
  • 打开package.json在scrips中加入cleanLibbableBuildprepublish

    {
      "name": "zppsakura-npm-demo",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "test": "echo "Error: no test specified" && exit 1",
        "cleanLib":"./node_modules/.bin/rimraf lib",
        "bableBuild":"./node_modules/.bin/babel src --out-dir lib",
        "prepublish":"npm run cleanLib && npm run bableBuild"
      },
      "keywords": [],
      "author": "zhoupan222",
      "license": "ISC",
      "dependencies": {
        "babel-cli": "^6.26.0",
        "babel-preset-es2015": "^6.24.1",
        "rimraf": "^3.0.2"
      }
    }
    

    cleanLib 用来清理lib中已有的内容
    bableBuild 用bable把src中的文件打包编译到lib中
    prepublish 执行上面两个脚本,prepublish会在npm publish前执行

  • 在项目的根目录创建.babelrc文件

    {
    	"presets": [
    		"es2015"
    	]
    }
    
  • 上npm注册账号,并进行邮箱验证

  • 登录npm,并正确填写用户名,密码,邮箱

    npm login
    
  • 发布

    npm publish
    
  • 删除包

    npm unpublish --force //强制删除
    npm unpublish guitest@1.0.1 //指定版本号
    

坑:

  • 包名重复(没有权限发布)npm包中的包名必须唯一!

    修改文件名以及package.json中的name名
    
  • 邮箱未验证

    进入官网验证邮箱
    
  • 需要登录

    npm login
    
  • 只有管理员才有权限进行发布

    修改镜像源,将淘宝源改成默认的

    npm config set registry https://registry.npmjs.org
    
  • 包名过于类似

    修改文件名及包名
    
  • 无法发布到私有包

    因为私有包时需要付费的,因此包名不能以 @your-name 开头,因为 @your-name 开头的包会默认发布为私有包
    
  • 网络超时

原文地址:https://www.cnblogs.com/zpsakura/p/14480448.html