微信小程序自定义组件库并发布到私有 npm 仓库

小程序 npm About 1,240 words

安装官方命令行

npm install -g @wechat-miniprogram/miniprogram-cli

初始化工程

miniprogram init --type custom-component 

安装依赖

npm install

新建组件

src下新建组件my-viewindex.json设置属性"component": true,在index.wxml中自定义界面。

├── LICENSE
├── README.md
├── gulpfile.js
├── package.json
├── src
│             └── my-view
│                 ├── index.js
│                 ├── index.json
│                 ├── index.wxml
│                 └── index.wxss
├── tools
│             ├── build.js
│             ├── checkcomponents.js
│             ├── checkwxss.js
│             ├── config.js
│             └── utils.js
└── tsconfig.json

config.js 设置

tools/config.js文件中,添加组件入口,有多个组件则在entry数组中继续添加。

module.exports = {
  entry: ['my-view/index'],
  ...
}

生成测试包

npm run dev

打包

npm run build

发布

设置私有仓库地址

npm config set registry http://my-npm-repo.com

登录 npm

npm login

发布 package

npm publish

工程中使用自定义组件

安装组件

npm install my-view

package.json

执行了安装组件命令后,在package.json中会添加以后配置。

并且会生成node_modules文件夹。

{
  "dependencies": {
    "my-view": "1.0.0"
  }
}

关键步骤

在微信开发者工具顶部菜单栏中的工具菜单下,选择构建npm

此时工程目录中会出现miniprogram_npm文件夹。

引用组件

在页面的index.json中使用添加配置。

{
  "usingComponents": {
    "my-view": "/miniprogram_npm/my-view/index"
  }
}

官方命令行开源链接

https://github.com/wechat-miniprogram/miniprogram-cli

Views: 293 · Posted: 2024-02-09

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh