一、注册npm账号

  • 怎么将代码提到github,大家都知道需要一个github账号
  • 同样,开发一个npm包,当然也需要一个npm账号,将npm包发布到npm的托管服务器
  • 注册地址:http://npmjs.org

二、开发npm包

1.目录构建

  • npm init
  • 项目结构:
    .
    ├── build // 打包配置文件
    ├── dist // 打包后文件
    ├── min // 压缩后的文件
    ├── src // 源代码
    ├── README.md //说明文档
    ├── package.json //包信息
    └── test //测试用例

2.开发模块

  • 入口src/index.js模块
    非全局安装(npm install xxx),则所有的函数接口都通过index.js暴露给外部调用


    const getDevice = require('./get/getDevice')

    module.exports = {
    getDevice
    }
  • src/get/getDevice.js模块


    function getDevice() {
    var userAgent = 'navigator' in window && 'userAgent' in navigator && navigator.userAgent.toLowerCase() || '';
    var vendor = 'navigator' in window && 'vendor' in navigator && navigator.vendor.toLowerCase() || '';
    var appVersion = 'navigator' in window && 'appVersion' in navigator && navigator.appVersion.toLowerCase() || '';

    if (/mac/i.test(appVersion)) return 'MacOSX'
    if (/win/i.test(appVersion)) return 'windows'
    if (/linux/i.test(appVersion)) return 'linux'
    if (/iphone/i.test(userAgent) || /ipad/i.test(userAgent) || /ipod/i.test(userAgent)) 'ios'
    if (/android/i.test(userAgent)) return 'android'
    if (/win/i.test(appVersion) && /phone/i.test(userAgent)) return 'windowsPhone'
    }

    module.exports = getDevice;

3.配置全局命令

build目录下写webpack配置代码

  • build.js

    const path = require('path')
    const fs = require('fs')
    const ora = require('ora') // 命令行环境的 loading效果
    const rm = require('rimraf') // 用于统一rm
    const copy = require('copy')
    const chalk = require('chalk') // 打印提示语
    const webpack = require('webpack')

    const config = require('./webpack.conf')
    const pkg = require('../package.json')
    const rootPath = path.resolve(__dirname, '../')

    new Promise((resolve, reject) => {
    // 构建全量压缩包
    let building = ora('building...')
    building.start()
    rm(path.resolve(rootPath, 'min', `*.js`), err => {
    if (err) throw (err)
    webpack(config, function (err, stats) {
    if (err) throw (err)
    building.stop()
    process.stdout.write(stats.toString({
    colors: true,
    modules: true,
    children: false,
    chunks: false,
    chunkModules: false
    }) + '\n\n')
    resolve()
    console.log(chalk.cyan(' Build complete.\n'))
    })
    })
    }).then(() => {
    // 替换模块文件
    let copying = ora('copying...')
    copying.start()
    rm('*.js', err => {
    if (err) throw (err)
    let folderList = fs.readdirSync(path.resolve(rootPath, 'src'))
    folderList.forEach((item, index) => {
    copy(`src/${item}/*.js`, rootPath + '/dist', function (err, files) {
    if (err) throw err;
    if (index === folderList.length - 1) {
    copying.stop()
    console.log(chalk.cyan(' Copy complete.\n'))
    }
    })
    })
    })
    }).catch((err) => {
    throw err
    })
  • webpack.conf.js

const webpack = require('webpack')
const path = require('path')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin') // 压缩代码


const pkg = require('../package.json')

const rootPath = path.resolve(__dirname, '../')

const config = {
entry: path.resolve(rootPath, 'src', 'index.js'),
output: {
filename: `${pkg.name}.min.js`,
path: path.resolve(rootPath, 'min'),
library: `${pkg.name}`,
libraryTarget: "umd"
},
module: {
rules: [{
test: /\.js$/,
loader: "babel-loader"
}]
},
plugins: [
new UglifyJsPlugin()
]
}

module.exports = config

三、发布npm包

1.npm login 登录npm帐号

npm login

2.npm run build 编译代码

npm run build

3.npm publish 发布

npm publish

四、常见问题

1. npm publish出错

npm ERR! publish Failed PUT 403
npm ERR! Darwin 16.0.0
npm ERR! argv "/usr/local/Cellar/node/5.6.0/bin/node" "/usr/local/bin/npm" "publish"
npm ERR! node v5.6.0
npm ERR! npm v3.10.3
npm ERR! code E403

npm ERR! "You cannot publish over the previously published version 0.0.43." : npm-develop
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR! <https://github.com/npm/npm/issues>

npm ERR! Please include the following file with any support request:
npm ERR! /Volumes/work/private/github/npm-develop/npm-debug.log

没有更新package.json的版本号,每次的版本号必须大于上次,否则无法publish

2. 采用sudo npm publish

password应该输入的是本机开机密码,非npm账号密码

转载请标注原文地址