# 搭建一个方法库
本文讲述如何搭建一个自己的js常用方法库,并引入typescript,打包工具使用rollup。
# 开始搭建
# package.json
- 执行npm init生成package.json文件,并安装下列typescript和rollup相关依赖
"devDependencies": {
    "rollup": "^2.38.0",
    "rollup-plugin-commonjs": "^10.1.0",
    "rollup-plugin-node-resolve": "^5.2.0",
    "rollup-plugin-typescript": "^1.0.1",
    "tslib": "^2.1.0",
    "typescript": "^4.1.3"
}
在"scripts"中添加打包命令
"scripts": {
    "build": "rollup -c"
}
# tsconfig.json
- 执行tsc --init自动生产typescript配置文件,可根据自己的需要进行配置(参考 (opens new window)),本文示例未作更改
# rollup.config.js
- 在根目录创建一个rollup.config.js文件,配置如下,可根据自己的需要进行更改(文档 (opens new window))
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import typescript from 'rollup-plugin-typescript';
export default {
  input: 'src/index.ts', // 入口文件
  output: {
    name: 'dc-utils', // 生成包名称
    file: 'dist/index.js', // 打包出口
    format: 'umd', // umd是兼容amd/cjs/iife的通用打包格式,适合浏览器
  },
  plugins: [
    resolve(), // 查找和打包node_modules中的第三方模块
    commonjs(), // 将 CommonJS 转换成 ES2015 模块供 Rollup 处理
    typescript() // 解析TypeScript
  ]
};
# src
- 完成配置后即可编写自己的具体方法库内容,建立一个src文件件,建一个index.ts文件作为入口文件,建一个getDate.ts文件
getDate.ts
// 格式化日期:yyyy-MM-dd
function formatDate(date: Date): string {
    let year: number = date.getFullYear();
    let month: number = date.getMonth() + 1;
    let day: number = date.getDate();
    return year + "-" + month + "-" + day;
}
export { formatDate }
index.ts
import * as getDate from './getDate';
var utils = {
    ...getDate
}
export default utils;
# 打包与测试
- 执行 - npm run build命令,即可看到项目目录生成的dist打包文件
- 将README.md和package.json复制到打包出来的文件夹下,进入该目录执行 - npm login和- npm publish发布方法库。 此处我将示例的包命名为@dc/cli发布在私有库上,私有库的搭建可参考在docker中通过Verdaccio搭建一个私有npm库 (opens new window)
最终目录结构
 
 npm私有库
 
 - 在项目中安装该方法库,引入依赖,即可正常使用
import utils from "@dc/utils";
console.log(utils.formatDate(new Date()))
← 搭建一个脚手架工具 搭建一个自动化部署服务 →