开始构建
首先安装一个全局库 vue-sfc-rollup
npm install -g vue-sfc-rollup
安装完成后,在命令行窗口进入想要在其中保存项目文件的目录,执行如下命令来初始化项目
sfc-init
在提示中选择如下选项:
- Is this a single component or a library? Library
- What is the npm name of your library? (名称在 npm 中必须是唯一的,这里我使用的是 amme-lib)
- Will this library be written in JavaScript or TypeScript? JavaScript(可以放心地选择 TypeScript,只要你清楚自己的选择)
- Enter a location to save the library files: (项目的文件夹名称,默认为之前步骤设置的 npm 名称,所以可以直接按 enter 取默认值。)
运行
设置完成之后,进入项目目录并执行 npm install
cd amme-lib
npm install
执行npm run serve,然后访问http://localhost:8080/查看效果,如下图
发布到npm
由于这是我们组件库的第一次发布,建议在执行 build 命令之前在 package.json文件中将版本号设置为 0.0.1,然后进行打包
npm run build
接下来将你的 NPM 账户添加到终端(terminal)tips: 请确保你有一个npm账号
npm adduser
笔者在此遇到了一个小问题
403 Forbidden - PUT https://registry.npmjs.org/amme-lib - Forbidden查证后发现
npm镜像不可以是淘宝镜像 顺带附带下切换方法及查看方式
npm config set registry https://registry.npmjs.org/
npm config get registry
如果需要使用淘宝镜像,建议使用cnpm
npm install -g cnpm --registry=https://registry.npm.taobao.org
发布
npm publish
登陆npm官网查看已发布的包
安装已发布的npm包
npm install amme-lib