一、注册 npm 账号

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

二、开发 npm 包

1.目录构建

  • npm init
  • 项目结构:
.
├── build           // 打包配置文件
├── dist            // 打包后文件
├── 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

四、常用命令

查看npm命令:

$ npm help

初始化

一个基于node的项目,会创建一个配置文件package.json(两种方式):

 //1.一般情况下 一路enter
 $ npm init

 //2.全部使用默认配置
 $ npm init --yes

安装模块(包):

//全局安装
$ npm install 模块名 -g
//本地安装
$ npm install 模块名
//一次性安装多个
$ npm install 模块1 模块2 模块n --save

//安装运行时依赖包
$ npm install 模块名 --save
//安装开发时依赖包
$ npm install 模块名 --save-dev

查看安装目录:

//查看本地安装的目录
$ npm root

//查看全局安装的目录
$ npm root -g

卸载模块(包):

//卸载本地模块
$ npm uninstall 模块名

//卸载全局模块
$ npm uninstall -g 模块名

更新模块(包)

$ npm update 模块名

$ npm update 模块名 -g

查看当前安装的模块(包)

$ npm ls

$ npm ls -g

查看模块(包)的信息:

$ npm info 模块名

五、常见问题

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