解决:npark-icon If this is a native custom element, make sure to exclude it from component resolution via compilerOptions.isCustomElement

在引入字节跳动开源的 iconPark 图标库时控制台提示以下提醒,但是效果并不影响,图标能够正常显示。后来我查阅了大量的资料总结出了解决的办法:

提醒信息

Failed to resolve component: iconpark-icon If this is a native custom element, make sure to exclude it from component resolution via compilerOptions.isCustomElement

提醒的原因

这种报错通常是因为在 Vue.js 应用程序中使用了自定义组件,但是在编译选项中没有将其排除在组件解析之外。

vue.config.js

  1. Vue.js 应用程序的根目录下创建 vue.config.js 文件(如果已经有该文件,则跳过此步骤)。
  2. 在 vue.config.js 文件中添加以下内容:
module.exports = {
  chainWebpack: config => {
    config.module.rule('vue').use('vue-loader').tap(options => {
      options.compilerOptions = {
        ...options.compilerOptions,
        isCustomElement: tag => tag.startsWith('iconpark-')
      }
      return options
    })
  }
}

这将告诉 Vue.js 编译器将所有以 iconpark- 开头的标签视为自定义组件,并将它们排除在组件解析之外。这样就不会包以上的提醒了

vite.config.js

如果你的 Vue.js 应用程序使用的是 Vite 构建工具,那么你需要在 Vite 配置文件中进行相应的配置,以将自定义元素排除在组件解析之外。

你可以按照以下步骤操作:

Vue.js 应用程序的根目录下创建 vite.config.js 文件(如果已经有该文件,则跳过此步骤)。

vite.config.js 文件中添加以下内容:

import vue from '@vitejs/plugin-vue'

export default {
  plugins: [
    vue({
      template: {
        compilerOptions: {
          isCustomElement: tag => tag.startsWith('iconpark-')
        }
      }
    })
  ]
}

这将告诉 Vue.js 编译器将所有以 iconpark- 开头的标签视为自定义组件,并将它们排除在组件解析之外。

重新启动 Vite 服务,然后尝试使用 <iconpark-icon> 组件,看看是否还会出现警告信息。

注意: 如果你的 Vue.js 应用程序使用了单文件组件(.vue 文件),则需要在 @vitejs/plugin-vue 插件中添加相应的选项,以确保编译器可以正确地识别自定义元素。上面的代码片段已经包含了这个选项,你可以直接使用。

BUG
评论区
头像