---
title: 发布组件
summary: "介绍如何将自定义组件发布到 npm 以及在项目中安装和引用 npm 组件的方法。"
questions:
  - 智能小程序自定义组件支持发布到哪里？
  - 发布组件的推荐文件结构包含哪些目录和文件？
  - .npmignore 文件的作用是什么？
  - 如何打包自定义组件？
  - 发布 npm 包时邮箱验证不通过会出现什么错误？
  - 如何在项目中安装和引用已发布的 npm 组件？
  - package.json 中 files 字段的作用是什么？
---

# 发布组件

智能小程序原生支持引入第三方 npm 模块。因此，自定义组件也支持发布到 npm，方便开发者复用和分享。

以下是发布组件的推荐文件结构，仅供参考。

```
├── foo // 单个组件文件夹
│   ├── index.js
│   ├── index.json
│   ├── index.tyml
│   ├── index.tyss
├── pages // 页面用于开发调试预览
│   ├── index.js
│   ├── index.json
│   ├── index.tyml
│   ├── index.tyss
├── app.js
├── app.json
├── app.tyss
├── project.tuya.json
├── package.json
└── .npmignore
```

## .npmignore

npm 忽略发布的文件列表。

```
app.*
pages/
project.tuya.json
```

## package.json

```json
{
  "name": "your-custom-component",
  "version": "1.0.0",
  "description": "your-custom-component",
  "repository": {
    "type": "git",
    "url": "your-custom-component-repository-url"
  },
  "files": ["es"],
  "keywords": ["custom-component", "smart-program"]
}
```

## 上传组件到 npm

### 1. 打包组件

运行 `npm run dist`，生成生产环境构建目录。

### 2. 注册 npm 账号

进入 npm 官网，注册账号。

**注意**：若验证邮箱不通过，发布时会出现 E403 错误。

### 3. 登录账号并发布

1. 登录注册的账号：
   npm login\npm adduser
2. 查看是否登录成功：
   npm whoami
3. 发布组件包：
   npm publish
   发布成功后，可在 npm 的个人中心的 `Packages` 里看到。

## 使用 npm 组件

### 安装包到项目中

```
npm install your-custom-component
```

### 引用组件

```json
{
  "usingComponents": {
    "foo": "your-custom-component/foo/index"
  }
}
```
