一、easycom的配置

easycom的默认规则适用于大多数场景,

但你可以通过pages.json中的easycom字段自定义匹配规则,

以满足特殊需求。

这是高级玩法了,自定义匹配规则;

1 - 基础配置 - pages.json

// pages.json
{
  "easycom": {
    "autoscan": true, // 是否自动扫描组件(默认true)
    "custom": {
      // 自定义匹配规则(键:组件标签名正则;值:组件文件路径模板)
      "^uni-": "uni-ui/lib/uni-*/uni-*.vue", // 匹配uni-ui组件(如<uni-button>)
      "^my-": "components/my-*/my-*.vue"    // 匹配自定义组件(如<my-component>)
    }
  }
}

2 - 配置项说明

配置项类型默认值说明
autoscanBooleantrue是否自动扫描项目中的组件文件
customObject{}自定义匹配规则(键:组件标签名正则;值:组件文件路径模板)

3 - 自定义规则示例

例如,

你有一个组件放在src/components/common/button.vue,

想通过<app-button>标签使用,

可以配置:

"easycom": {
  "custom": {
    "^app-(.*)": "src/components/common/$1.vue" // 正则匹配:app-button -> common/button.vue
  }
}

二、easycom的使用场景

1 - 自定义组件

创建一个符合easycom规范的组件:

  • 组件文件路径:components/my-card/my-card.vue

  • 组件内容:

<!-- my-card.vue -->
<template>
  <div class="my-card">{{title}}</div>
</template>

<script>
export default {
  props: ['title']
}
</script>
  • 页面中使用(无需导入/注册)
<template>
  <my-card title="Hello easycom!" />
</template>

2 - 第三方组件库(如uni-ui)

uni-ui是UniApp官方组件库,所有组件都支持easycom。

例如使用 <uni-button>:

  • 安装uni-ui:npm install @dcloudio/uni-ui

  • 页面中直接使用:

<template>
  <my-card title="Hello easycom!" />
</template>

3 - 动态组件 - 有意思

easycom支持动态组件(component标签),

例如:

<template>
  <component :is="componentName" />
</template>
<script>
export default {
  data() {
    return {
      componentName: 'my-card' // 对应组件文件my-card.vue
    }
  }
}
</script>

三、easycom的优势

1、减少代码冗余

无需手动写import和components注册代码,模板更简洁。

2、提高开发效率

组件使用更直观,无需记忆组件路径。

3、支持第三方组件库

如uni-ui、uView等,直接使用组件标签即可。

4、动态组件友好

动态切换组件时,无需提前注册所有可能的组件。

四、注意事项

1 - 组件命名规范

  • 组件文件名需使用小写 + 短横线(如 my-component.vue),

避免大驼峰(如MyComponent.vue),

否则默认规则无法匹配。

  • 组件标签名需与文件名一致(如<my-component>对应my-component.vue)。

2 - 排除特定组件

如果某些组件不需要自动导入,可以在easycom配置中排除。

"easycom": {
  "custom": {
    "^uni-": "uni-ui/lib/uni-*/uni-*.vue",
    "exclude": ["uni-ui/lib/uni-button/uni-button.vue"] // 排除uni-button组件
  }
}

3 - 多出口组件

如果组件文件导出多个组件(如 export { ComponentA, ComponentB }),

easycom无法自动识别,需手动导入。

4 - 编译时处理

easycom是编译时机制,

修改组件文件后,

编译器会自动更新,

无需重启项目。

五、总结

easycom是UniApp中最实用的特性之一,

通过约定大于配置的方式,

彻底解决了组件导入/注册的繁琐问题。

无论是自定义组件还是第三方组件库,

都能通过easycom快速使用,

极大提升了开发效率。


关键结论:

  • 组件文件名 = 组件标签名(小写 + 短横线);

  • 组件文件放在components目录下(或自定义路径);

  • 无需手动导入/注册,直接使用组件标签。


如果需要更灵活的配置,

可以通过pages.json中的easycom字段调整匹配规则,

满足项目的特殊需求。

更多推荐