Giter VIP home page Giter VIP logo

unplugin-vue-components's Introduction

unplugin-vue-components

NPM version

On-demand components auto importing for Vue.

Features
  • 💚 Supports both Vue 2 and Vue 3 out-of-the-box.
  • ✨ Supports both components and directives.
  • ⚡️ Supports Vite, Webpack, Rspack, Vue CLI, Rollup, esbuild and more, powered by unplugin.
  • 🏝 Tree-shakable, only registers the components you use.
  • 🪐 Folder names as namespaces.
  • 🦾 Full TypeScript support.
  • 🌈 Built-in resolvers for popular UI libraries.
  • 😃 Works perfectly with unplugin-icons.


Installation

npm i unplugin-vue-components -D

vite-plugin-components has been renamed to unplugin-vue-components, see the migration guide.

Vite
// vite.config.ts
import Components from 'unplugin-vue-components/vite'

export default defineConfig({
  plugins: [
    Components({ /* options */ }),
  ],
})


Rollup
// rollup.config.js
import Components from 'unplugin-vue-components/rollup'

export default {
  plugins: [
    Components({ /* options */ }),
  ],
}


Webpack
// webpack.config.js
module.exports = {
  /* ... */
  plugins: [
    require('unplugin-vue-components/webpack').default({ /* options */ }),
  ],
}


Rspack
// rspack.config.js
module.exports = {
  /* ... */
  plugins: [
    require('unplugin-vue-components/rspack').default({ /* options */ }),
  ],
}


Nuxt

You might not need this plugin for Nuxt. Use @nuxt/components instead.


Vue CLI
// vue.config.js
module.exports = {
  /* ... */
  plugins: [
    require('unplugin-vue-components/webpack').default({ /* options */ }),
  ],
}

You can also rename the Vue configuration file to vue.config.mjs and use static import syntax (you should use latest @vue/cli-service ^5.0.8):

// vue.config.mjs
import Components from 'unplugin-vue-components/webpack'

export default {
  configureWebpack: {
    plugins: [
      Components({ /* options */ }),
    ],
  },
}


esbuild
// esbuild.config.js
import { build } from 'esbuild'
import Components from 'unplugin-vue-components/esbuild'

build({
  /* ... */
  plugins: [
    Components({
      /* options */
    }),
  ],
})


Usage

Use components in templates as you would usually do, it will import components on demand, and there is no import and component registration required anymore! If you register the parent component asynchronously (or lazy route), the auto-imported components will be code-split along with their parent.

It will automatically turn this

<template>
  <div>
    <HelloWorld msg="Hello Vue 3.0 + Vite" />
  </div>
</template>

<script>
  export default {
    name: 'App',
  }
</script>

into this

<template>
  <div>
    <HelloWorld msg="Hello Vue 3.0 + Vite" />
  </div>
</template>

<script>
  import HelloWorld from './src/components/HelloWorld.vue'

  export default {
    name: 'App',
    components: {
      HelloWorld,
    },
  }
</script>

Note By default this plugin will import components in the src/components path. You can customize it using the dirs option.

TypeScript

To get TypeScript support for auto-imported components, there is a PR to Vue 3 extending the interface of global components. Currently, Volar has supported this usage already. If you are using Volar, you can change the config as following to get the support.

Components({
  dts: true, // enabled by default if `typescript` is installed
})

Once the setup is done, a components.d.ts will be generated and updates automatically with the type definitions. Feel free to commit it into git or not as you want.

Make sure you also add components.d.ts to your tsconfig.json under include.

Importing from UI Libraries

We have several built-in resolvers for popular UI libraries like Vuetify, Ant Design Vue, and Element Plus, where you can enable them by:

Supported Resolvers:

// vite.config.js
import Components from 'unplugin-vue-components/vite'
import {
  AntDesignVueResolver,
  ElementPlusResolver,
  VantResolver,
} from 'unplugin-vue-components/resolvers'

// your plugin installation
Components({
  resolvers: [
    AntDesignVueResolver(),
    ElementPlusResolver(),
    VantResolver(),
  ],
})

You can also write your own resolver quickly:

Components({
  resolvers: [
    // example of importing Vant
    (componentName) => {
      // where `componentName` is always CapitalCase
      if (componentName.startsWith('Van'))
        return { name: componentName.slice(3), from: 'vant' }
    },
  ],
})

We no longer accept new resolvers.

Types for global registered components

Some libraries might register some global components for you to use anywhere (e.g. Vue Router provides <RouterLink> and <RouterView>). Since they are global available, there is no need for this plugin to import them. However, those are commonly not TypeScript friendly, and you might need to register their types manually.

Thus unplugin-vue-components provided a way to only register types for global components.

Components({
  dts: true,
  types: [{
    from: 'vue-router',
    names: ['RouterLink', 'RouterView'],
  }],
})

So the RouterLink and RouterView will be presented in components.d.ts.

By default, unplugin-vue-components detects supported libraries automatically (e.g. vue-router) when they are installed in the workspace. If you want to disable it completely, you can pass an empty array to it:

Components({
  // Disable type only registration
  types: [],
})

Migrate from vite-plugin-components

package.json

{
  "devDependencies": {
-   "vite-plugin-components": "*",
+   "unplugin-vue-components": "^0.14.0",
  }
}

vite.config.js

- import Components, { ElementPlusResolver } from 'vite-plugin-components'
+ import Components from 'unplugin-vue-components/vite'
+ import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'

export default {
  plugins: [
    /* ... */
    Components({
      /* ... */

      // `customComponentsResolvers` has renamed to `resolver`
-     customComponentsResolvers: [
+     resolvers: [
        ElementPlusResolver(),
      ],

      // `globalComponentsDeclaration` has renamed to `dts`
-     globalComponentsDeclaration: true,
+     dts: true,

      // `customLoaderMatcher` is depreacted, use `include` instead
-     customLoaderMatcher: id => id.endsWith('.md'),
+     include: [/\.vue$/, /\.vue\?vue/, /\.md$/],
    }),
  ],
}

Configuration

The following show the default values of the configuration

Components({
  // relative paths to the directory to search for components.
  dirs: ['src/components'],

  // valid file extensions for components.
  extensions: ['vue'],

  // Glob patterns to match file names to be detected as components.
  // When specified, the `dirs`, `extensions`, and `directoryAsNamespace` options will be ignored.
  // If you want to exclude components being registered, use negative globs with leading `!`.
  globs: ['src/components/*.{vue}'],

  // search for subdirectories
  deep: true,

  // resolvers for custom components
  resolvers: [],

  // generate `components.d.ts` global declarations,
  // also accepts a path for custom filename
  // default: `true` if package typescript is installed
  dts: false,

  // Allow subdirectories as namespace prefix for components.
  directoryAsNamespace: false,

  // Collapse same prefixes (camel-sensitive) of folders and components
  // to prevent duplication inside namespaced component name.
  // works when `directoryAsNamespace: true`
  collapseSamePrefixes: false,

  // Subdirectory paths for ignoring namespace prefixes.
  // works when `directoryAsNamespace: true`
  globalNamespaces: [],

  // auto import for directives
  // default: `true` for Vue 3, `false` for Vue 2
  // Babel is needed to do the transformation for Vue 2, it's disabled by default for performance concerns.
  // To install Babel, run: `npm install -D @babel/parser`
  directives: true,

  // Transform path before resolving
  importPathTransform: v => v,

  // Allow for components to override other components with the same name
  allowOverrides: false,

  // Filters for transforming targets (components to insert the auto import)
  // Note these are NOT about including/excluding components registered - use `globs` or `excludeNames` for that
  include: [/\.vue$/, /\.vue\?vue/],
  exclude: [/[\\/]node_modules[\\/]/, /[\\/]\.git[\\/]/, /[\\/]\.nuxt[\\/]/],

  // Filters for component names that will not be imported
  // Use for globally imported async components or other conflicts that the plugin cannot detect
  excludeNames: [/^Async.+/],

  // Vue version of project. It will detect automatically if not specified.
  // Acceptable value: 2 | 2.7 | 3
  version: 2.7,

  // Only provide types of components in library (registered globally)
  types: []
})

Example

Vitesse starter template.

Thanks

Thanks to @brattonross, this project is heavily inspired by vite-plugin-voie.

License

MIT License © 2020-PRESENT Anthony Fu

unplugin-vue-components's People

Contributors

antfu avatar azaleta avatar danranvm avatar dblazhkun avatar flsion avatar ga676005 avatar hannoeru avatar haoziqaq avatar johncampionjr avatar kaelwd avatar kanade-lu avatar ky-is avatar leejim avatar libondev avatar lishaobos avatar lizhequ avatar markthree avatar miyukoarc avatar nabaonan avatar patrickchen928 avatar rafaelytakei avatar sight-wcg avatar sxzz avatar talljack avatar userquin avatar uyarn avatar vividlemon avatar yangyanggu avatar ycs77 avatar zyyv avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

unplugin-vue-components's Issues

Recursive components do not work without naming the component

I have a recursive component that uses itself. The root component is auto imported and works, but calling the same component from the component wont.

But if you name the component, then it works.

Example:

<template>
    <div>
        <my-comp v-if="!level" :level="level+1"/>
    </div>
</template>

<script>
// src/components/my-comp.vue
export default {
    //name: 'my-comp', // COMPONENT RECURSION DO NOT WORK WITHOUT THIS LINE
    props: {
        level : { default: 0 }
    }
}
</script>

Support kebab-case component names

I'd like to be able to use kebab-casing in my templates. Currently, the casing appears to have to match the file name.

For example, if I have the component HelloWorld.vue then I must use <HelloWorld /> in my template. I'd instead like to use <hello-world />

0.6.7 and newer aren't finding components on Windows

(Haven't yet tested on Mac)

0.6.6 debugging of sample in Windows

  vite-plugin-components:glob started with: [src/components/**/*.{vue,md}] +0ms
  vite-plugin-components:glob 11 components found. +7ms

0.6.7 debugging

vite-plugin-components:glob started with: [C:\Data\Git\vite-plugin-components\example\src\components/**/*.{vue,md}] +0ms
  vite-plugin-components:glob 0 components found. +9ms 

Looks like the path is getting added to the wrong place.

Require fast-glob

Last version requires fast-glob package to work. It is included at your package.json but seems pointing to a private package or a kind of specific version.
I need to install it manually into my own package.json to the plugin work properly. It happens with all my Vite apps.
By installing fast-glob at devDependencies I have "fast-glob": "^3.2.5" and it works.

After install and setup the plugin, before install fast-glob:

$ npm start

> [email protected] start /home/alxbr/github/link-web-apps/online-video-conf/hosting
> vite --debug

failed to load config from /home/alxbr/github/link-web-apps/online-video-conf/hosting/vite.config.js
error when starting dev server:
Error: Cannot find module 'fast-glob'
Require stack:
- /home/alxbr/github/link-web-apps/online-video-conf/hosting/node_modules/vite-plugin-components/dist/index.js
- /home/alxbr/github/link-web-apps/online-video-conf/hosting/vite.config.js
- /home/alxbr/github/link-web-apps/online-video-conf/hosting/node_modules/vite/dist/node/chunks/dep-e0f09032.js
- /home/alxbr/github/link-web-apps/online-video-conf/hosting/node_modules/vite/dist/node/cli.js
- /home/alxbr/github/link-web-apps/online-video-conf/hosting/node_modules/vite/bin/vite.js
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:880:15)
    at Function.Module._load (internal/modules/cjs/loader.js:725:27)
    at Module.require (internal/modules/cjs/loader.js:952:19)
    at require (internal/modules/cjs/helpers.js:88:18)
    at Object.<anonymous> (/home/alxbr/github/link-web-apps/online-video-conf/hosting/node_modules/vite-plugin-components/dist/index.js:196:17)
    at Module._compile (internal/modules/cjs/loader.js:1063:30)
    at Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Object.require.extensions.<computed> [as .js] (/home/alxbr/github/link-web-apps/online-video-conf/hosting/node_modules/vite/dist/node/chunks/dep-e0f09032.js:48590:13)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] start: `vite --debug`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the [email protected] start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/alxbr/.npm/_logs/2021-03-13T19_12_32_691Z-debug.log

使用 vite-plugin-icons 配合 vite-plugin-components 该如何使用 component is

vite.config.js plugins中这样配置

ViteComponents({
      customComponentResolvers: ViteIconsResolver({
        componentPrefix: 'icon'
      })
    })

是否可以在组件中这样使用

<div v-for="(item, index) in list" :key="index">
    <component v-bind:is="item.icon" />
    {{ item.name }}
</div>
let list = [
  {
    icon: 'icon-mdi-account-convert',
    name: '按钮1'
  },
  {
    icon: 'icon-mdi-account-convert',
    name: '按钮2'
  }
]

如果不可以,是否有类似解决方案

Conflicting namespaces

when I use @antv/g6 with plugin, run vite build

console show
Conflicting namespaces: "node_modules/@antv/g6-pc/es/index.js" re-exports "Shape" from both "node_modules/@antv/g6-pc/es/index.js" and "node_modules/@antv/g6-core/es/index.js" (will be ignored) Conflicting namespaces: "node_modules/@antv/g6-pc/es/index.js" re-exports "Marker" from both "node_modules/@antv/g6-pc/es/index.js" and "node_modules/@antv/g6-core/es/index.js" (will be ignored) Conflicting namespaces: "node_modules/@antv/g6-pc/es/index.js" re-exports "Util" from both "node_modules/@antv/g6-pc/es/index.js" and "node_modules/@antv/g6-core/es/index.js" (will be ignored)

@antv/g6 not working

ElementPlusResolver(), error

using element gives the following errors

GET http://localhost:3333/@id/@vite-icons/el/button net::ERR_ABORTED 404 (Not Found) vue-router.esm-bundler.js:72 [Vue Router warn]: uncaught error during route navigation: warn @ vue-router.esm-bundler.js:72 triggerError @ vue-router.esm-bundler.js:3240 (anonymous) @ vue-router.esm-bundler.js:2977 Promise.catch (async) pushWithRedirect @ vue-router.esm-bundler.js:2974 push @ vue-router.esm-bundler.js:2909 install @ vue-router.esm-bundler.js:3323 use @ runtime-core.esm-bundler.js:4001 createApp2 @ index.mjs:34 (anonymous) @ index.mjs:63 ViteSSG @ index.mjs:65 (anonymous) @ main.ts:12 vue-router.esm-bundler.js:3242 TypeError: Failed to fetch dynamically imported module: http://localhost:3333/src/layouts/404.vue?t=1624293178771 triggerError @ vue-router.esm-bundler.js:3242 (anonymous) @ vue-router.esm-bundler.js:2977 Promise.catch (async) pushWithRedirect @ vue-router.esm-bundler.js:2974 push @ vue-router.esm-bundler.js:2909 install @ vue-router.esm-bundler.js:3323 use @ runtime-core.esm-bundler.js:4001 createApp2 @ index.mjs:34 (anonymous) @ index.mjs:63 ViteSSG @ index.mjs:65 (anonymous) @ main.ts:12 vue-router.esm-bundler.js:72 [Vue Router warn]: Unexpected error when starting the router: TypeError: Failed to fetch dynamically imported module: http://localhost:3333/src/layouts/404.vue?t=1624293178771 warn @ vue-router.esm-bundler.js:72 (anonymous) @ vue-router.esm-bundler.js:3325 Promise.catch (async) install @ vue-router.esm-bundler.js:3323 use @ runtime-core.esm-bundler.js:4001 createApp2 @ index.mjs:34 (anonymous) @ index.mjs:63 ViteSSG @ index.mjs:65 (anonymous) @ main.ts:12 ssss:1 Uncaught (in promise) TypeError: Failed to fetch dynamically imported module: http://localhost:3333/src/layouts/404.vue?t=1624293178771 Promise.then (async) install @ pwa.ts:8 (anonymous) @ main.ts:17 (anonymous) @ main.ts:17 createApp2 @ index.mjs:40 (anonymous) @ index.mjs:63 ViteSSG @ index.mjs:65 (anonymous) @ main.ts:12 index.mjs:65 Uncaught (in promise) TypeError: Failed to fetch dynamically imported module: http://localhost:3333/src/layouts/404.vue?t=1624293178771

Naming conflicts after updating to 0.7

I'm using the plugin with directoryAsNamespace: true, option. So for example I have my component app-header stored at components/app/header.vue. I worked fine until I've updated the version from 0.6.6 to 0.7.1. Now I have such errors in the console:

[vite-plugin-components] component "Card"(....../src/components/def/card.vue) has naming conflicts with other components, ignored.
[vite-plugin-components] component "List"(....../src/components/def/list.vue) has naming conflicts with other components, ignored.
[vite-plugin-components] component "Card"(......./src/components/link/card.vue) has naming conflicts with other components, ignored.
... and so on...

Looks like a bug. Or may be I need to make some changes to the config?

tsx not work load style

import { defineConfig } from 'vite';
import { resolve } from 'path';
import Vue from '@vitejs/plugin-vue';
import VueJsx from '@vitejs/plugin-vue-jsx';
import ViteComponents, { AntDesignVueResolver } from 'vite-plugin-components';

export default defineConfig({
  resolve: {
    alias: [
      {
        find: '@',
        replacement: resolve(__dirname, 'src'),
      },
    ],
  },
  plugins: [
    Vue(),
    VueJsx(),
    ViteComponents({
      deep: true,
      dirs: ['src'],
      extensions: ['vue', 'tsx'],
      customComponentResolvers: [AntDesignVueResolver()],
    }),
  ],
  css: {
    preprocessorOptions: {
      less: {
        javascriptEnabled: true,
      },
    },
    modules: {
      localsConvention: 'camelCase',
    },
  },
});

[Q&A]ant-design-vue with AntDesignVueResolver:unknown theme, type: undefined, name: undefined'

Vue2.x + Vite2.0 + ant-design-vue1.7.5

中文:
当我使用Ant-Design-Vue("ant-design-vue": "^1.7.5",)的时候
import ViteComponents, { AntDesignVueResolver } from "vite-plugin-components";
提示这样的报错,这个是否是Antd自身的问题?有解决方案吗?在其他也找过相关问题,但是没找到解决方案(顺便说下:新人小白,所以这个问题也许会浪费时间)


MT(machine translation)

When I use ant design Vue"ant-design-vue": "^1.7.5",
import ViteComponents, { AntDesignVueResolver } from "vite-plugin-components";
Prompt such an error. Is this the problem of antd itself? Is there a solution? I've found related problems in other places, but I haven't found a solution (btw: Newcomer,so this problem may be a waste of time)


Error Info:

utils.js:105 Uncaught TypeError: Unknown theme type: undefined, name: undefined
    at withSuffix (utils.js:105)
    at Icon.js:25
    at Array.forEach (<anonymous>)
    at Object.add (Icon.js:24)
    at index.js:18

vite.config.js

import ViteComponents, { AntDesignVueResolver } from "vite-plugin-components";

const config = defineConfig({
  plugins: [
    ViteComponents({
      customComponentResolvers: [
        AntDesignVueResolver(),
        ViteIconsResolver({
          componentPrefix: "",
        })
      ],
    }),
    // ViteIcons({
    //   defaultStyle: "",
    // }),
    // WindiCSS(),
  ],
});

The built-in AntDesignVueResolver method cannot load ant design vue component styles on demand

Directly use AntDesignVueResolver to load components on demand but fail to load styles

Use this method to :
import ViteComponents from 'vite-plugin-components'

plugins:[
ViteComponents({customComponentResolvers: [
(name: string) => {
if(name.match(/^A[A-Z]/)) return {
importName: name.slice(1),
path: 'ant-design-vue/es',
sideEffects: "ant-design-vue/es/style",
}
}
]})
]

I hope the author can check if there are health problems when building AntDesignVueResolver

1624864139(1)

Can't make type check for props work for global components with volar

Demo project

Hi! I've created a fresh vite app with this plugin, added globalComponentsDeclaration: true.
The file components.d.ts is generated, but vscode doesn't show me warnings of incorrect using of props, unless I import the component.

Button.vue:

<script setup lang="ts">
import { defineProps } from 'vue'

const props = defineProps({
  size: {
    type: String,
    required: true,
  },
})
</script>

Component is not imported (no type checks for props)
Screen Shot 2021-05-31 at 20 26 19

Component is imported, so type check works great.
Screen Shot 2021-05-31 at 20 27 13

I'm expecting to see something like that: https://twitter.com/antfu7/status/1397168229005463563 but can't figure out what's wrong.

And what's more strange, this feature is working perfectly if I install a new vitesse project.

use the plugin with vite-plugin-import-style, but style not loaded

config as follows:

// main.ts
import { createApp } from 'vue'
// import { Button } from 'ant-design-vue'
// import Antd from 'ant-design-vue'
import App from './App.vue'

import 'virtual:windi.css'

const app = createApp(App);

// app.use(Button)
// app.use(Antd)

app.mount('#root', true)
// vite.config.ts
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import ViteComponents, {
  AntDesignVueResolver
} from 'vite-plugin-components'
// import ViteCompression from 'vite-plugin-compression'
import ViteStyleImport from 'vite-plugin-style-import'
import WindiCSS from 'vite-plugin-windicss'

// https://vitejs.dev/config/
export default defineConfig({
  // 1. If you are using the ant-design series, you need to configure this
  // 2. Make sure less is installed in the dependency `yarn add less -D`
  css: {
    preprocessorOptions: {
      less: {
        // modifyVars: {},
        javascriptEnabled: true,
      },
    },
  },
  plugins: [
    vue(),

    // https://github.com/antfu/vite-plugin-components
    ViteComponents({
      globalComponentsDeclaration: true,
      customComponentResolvers: [
        AntDesignVueResolver(),
      ]
    }),

    // https://github.com/windicss/vite-plugin-windicss
    WindiCSS(),

    // https://github.com/anncwb/vite-plugin-compression
    // ViteCompression(),

    // https://github.com/anncwb/vite-plugin-style-import
    ViteStyleImport({
      libs: [
        {
          libraryName: 'ant-design-vue',
          esModule: true,
          resolveStyle: (name) => {
            return `ant-design-vue/es/${name}/style/index`;
          },
        }
      ]
    }),
  ]
})
<template>
  <a-button type="primary">Ant Button</a-button>
</template>

style not generate

image

what should i do

[Bug Report] vite-ssg with ElementPlusResolver()

When i use vite-ssg with vite-plugin-componsnts customComponentResolvers: [ElementPlusResolver()].
I will get Cannot use import statement outside a module.

/Users/yunyou/github/pages/sponsors/node_modules/.pnpm/[email protected][email protected]/node_modules/element-plus/es/el-tabs/index.js:1
(function (exports, require, module, __filename, __dirname) { import { defineComponent, inject, getCurrentInstance, ref, watch, nextTick, openBlock, createBlock, computed, onUpdated, onMounted, onBeforeUnmount, h, provide, Fragment } from 'vue';
                                                              ^^^^^^

SyntaxError: Cannot use import statement outside a module
    at new Script (vm.js:101:7)
    at p._moduleCompile (/Users/yunyou/github/pages/sponsors/node_modules/.pnpm/[email protected]/node_modules/jiti/dist/v8cache.js:2:3154)
    at Module.o._compile (/Users/yunyou/github/pages/sponsors/node_modules/.pnpm/[email protected]/node_modules/jiti/dist/v8cache.js:2:2705)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Module.require (internal/modules/cjs/loader.js:952:19)
    at n (/Users/yunyou/github/pages/sponsors/node_modules/.pnpm/[email protected]/node_modules/jiti/dist/v8cache.js:2:2472)
    at Module.<anonymous> (/Users/yunyou/github/pages/sponsors/.vite-ssg-temp/main.js:13:29)
    at Module.o._compile (/Users/yunyou/github/pages/sponsors/node_modules/.pnpm/[email protected]/node_modules/jiti/dist/v8cache.js:2:2778)

Steps to reproduce

Use vitesse.

npx degit antfu/vitesse my-vitesse-app
cd my-vitesse-app
npm i

Add element-plus.

npm add element-plus

Config element-plus.

// src/modules/element.ts
import { UserModule } from "~/types";

import ElementPlus from "element-plus";
import "element-plus/lib/theme-chalk/index.css";

export const install: UserModule = ({ app }) => {
  app.use(ElementPlus);
};
// vite.config.ts
export default defineConfig({
  ...
  ViteComponents({
    ...
    // auto import icons
    customComponentResolvers: [
      ElementPlusResolver()
    ],
  }),
  ...
})
// App.vue
<template>
  <router-view />
  <el-button>TEST</el-button>
</template>

At last, npm run build. We will get this error.

My Solution

Remove ElementPlusResolver(), and it works.

Other

https://github.com/antfu/vite-plugin-components/blob/5c0842971a75c4244da25a5bc6c57a9948165806/src/resolvers/element-plus.ts#L25

The export of element-plus is located in lib.

https://github.com/element-plus/element-plus/blob/9b74a3dd03541e8aca369f5dd57be4305b26a326/package.json#L152

// element-plus/package.json
{
  "main": "lib/index.js",
  "module": "lib/index.esm.js",
  "typings": "lib/index.d.ts",
  "unpkg": "lib/index.js",
  "style": "lib/theme-chalk/index.css",
}

And element-plus support on-demand import by vite-plugin-style-import. It use element-plus/lib/${name}.

https://element-plus.org/#/zh-CN/component/quickstart#an-xu-yin-ru

export default defineConfig({
  plugins: [
    vue(),
    styleImport({
      libs: [{
        libraryName: 'element-plus',
        esModule: true,
        ensureStyleFile: true,
        resolveStyle: (name) => {
          name = name.slice(3)
          return `element-plus/packages/theme-chalk/src/${name}.scss`;
        },
        resolveComponent: (name) => {
          return `element-plus/lib/${name}`;
        },
      }]
    })
  ]
})

So we can change element-plus/es/el-${partialName} to element-plus/lib/el-${partialName}.

If you think I am right, just tell me and I will create a PR for it.

bug: HeadlessUiResolver not generating types for components

vite.config.ts

customComponentResolvers: [
  HeadlessUiResolver()
]

is not generating types for the Headless UI components as expected. When I remove import { Listbox, ListboxButton, ListboxLabel, ListboxOption, ListboxOptions } from '@headlessui/vue'; then the components have no typings in the template.

Conflict with vite-plugin-vue2 when sourcemap enabled

If I enable sourcemap in vite config (build.sourceMap: true), then I'll get this strange error:
[vite] Internal server error: ENOENT: no such file or directory, open '/home/kromanov/Playground/vite-example/src/components/HelloWorld.vue?vue&type=style&index=0&scoped=true&lang.css'

Here you can check reproduction of the bug.
Try to do npm run dev, you'll see error.
Then disable sourcemap in vite config and run again. Error will gone.
https://github.com/Djaler/vite-vue2-components-sourcemap-bug

Does this work with vue3-runtime-template?

I added vite-plugin-components to my vite.config.js
I'm using a php stack with inertia and render runtime components with vue3-runtime-template

However, vue.esm-bundler.js says that my auto imported components can't be resolved.

the vue.esm-bundler.js is added as an alias 'vue'

resolve: {
      alias: {
        vue: 'vue/dist/vue.esm-bundler.js',
      },
    },

If i add

import Tabs from './components/ui/Tabs.vue'

and

.component('Tabs', Tabs)

my Tab component is rendered within the vue3-runtime-template component

Support Vue 2

Just following the docs while using Vue 2.
The plugin recognizes the component path, but doesn't seem to import the components.

ViteComponents({ dirs: ['./src/components'], })

Unknown custom element: <Test> - did you register the component correctly? For recursive components, make sure to provide the "name" option

<template>
    <div>
        test
    </div>
</template>

<script>
    export default {
        name: 'Test'
    }
</script>

<style lang="scss" scoped>

</style>

How to use this with unit tests?

As this is a vite plugin it won't be utilized when running unit test and all components won't be transformed.
Is there any trick to get this working with the vue-test-utils / jest?

Dynamic component support

Is this plugin support dynamic components? Such as using <component :is="" />
I tried to use this plugin using dynamic components, but it's not rendering.

Example:

<!-- rendered to <mybutton /> -->
<component :is="'myButton'" />

<!-- correctly rendered -->
<myButton>

Why component inside component not automatically loaded?

After solving the issue about How to configure for Element UI?, I get a new problem.

This is about, when using Element UI, there is a component inside a component, and this library not automatically loaded it. For example, inside the menu-item component there is tooltip component, which is used/showed when the menu collapsed.

Here the example when I use menu-item component without manually imported the tooltip component.

Tooltip problem

And here the example when I try to use tooltip on the same page (actually I don't need it in this page).

Manually import tooltip

And here is the menu-item code looks like, that using el-tooltip component.

menu-item component

So, how can we solve this problem?

I think this is about recursive component import.

Thanks in advance.

Could not load path ENOENT: no such file or directory, open 'path'

I'm getting the following error when trying to use vite-plugin-components inside a brand new Vite project:

[vite] Dep optimization failed with error:
Could not load path (imported by node_modules/vite-plugin-components/dist/index.mjs): ENOENT: no such file or directory, open 'path'

My vite.config.ts:

import { UserConfig } from "vite";
import VitePluginComponents from "vite-plugin-components";

const config: UserConfig = {
  plugins: [VitePluginComponents()],
};

export default config;

Update: It seems to only affect dev mode.

DirectoryAsNamespace doesnt work as intended!

Hey there,
so i just recently updated to the latest Version of vite-plugin-components (0.7.3) and directoryAsNamespace doesnt work anymore.

Expected:
ui/navigation.vue --> ui-navigation.vue

Current Output:
ui/navigation.vue --> navigation.vue

Test Repo will follow soon!

Vuetify custom scss variables

Vuetify allows customization using scss variables. The recommended way is to create a src/(scss|sass|styles)/variables.scss file with the variables.

This doesn't work out of the box with ViteComponents({ customComponentResolvers: VuetifyResolver() }).

I tried using vite's additionalData: vitejs/vite#832 but the variables seem to only be parsed for the project's scss files, not the scss files from vuetify.

I ended up writing a custom plugin:

function vuetifyScssPlugin() {
  return {
    name: "vuetify-scss-plugin",
    load(id) {
      if (/\/V[A-Z]\w+.sass$/.test(id)) {
        return '@import "@/scss/variables"\n' + fs.readFileSync(id);
      }
    },
  };
}

const config = defineConfig({
  plugins: [createVuePlugin(), vuetifyScssPlugin(), ViteComponents({ customComponentResolvers: VuetifyResolver() })],
  resolve: {
    alias: {
      "@": path.resolve(__dirname, "./src"),
    },
  },
});

The style is now fine but the build time is much slower.

ElCalendar i18n can not work

view.config.ts:

plugins: [
  vue(),
  WindiCSS(),
  ViteComponents({
    customComponentResolvers: [
      ElementPlusResolver(),
      name => {
        // auto import Headless UI
        // where `name` is always CapitalCase
        if (name.startsWith('Hl')) {
          return { importName: name.slice(2), path: '@headlessui/vue' }
        }
      },
    ],
  }),
  PurgeIcons(),
  styleImport({
    libs: [
      {
        libraryName: 'element-plus',
        esModule: true,
        ensureStyleFile: true,
        resolveStyle: name => {
          name = name.slice(3)
          return `element-plus/packages/theme-chalk/src/${name}.scss`
        },
        resolveComponent: name => {
          return `element-plus/lib/${name}`
        },
      },
    ],
  }),
]

element.ts:

import {
  ElIcon,
  ElLoading,
  locale,
} from 'element-plus'
import lang from 'element-plus/lib/locale/lang/zh-cn'
locale(lang)

node: 16.0.0
vite: 2.2.4
vite-plugin-components: 0.8.4
element-plus: 1.0.2-beta.41

image

How to configure for Element UI?

I try to use this awesome library to my Vue 2 project with Element UI. But keep getting errors.

Here is my custom config:

ViteComponents({
  customComponentResolvers: [
    (name) => {
      if (name.startsWith('El'))  { // Element UI
        const partialName = paramCase(name.slice(2)) // e.g. ElButton -> button
        return {
          name: partialName,
          path: 'element-ui/lib',
          sideEffects: `element-ui/packages/theme-chalk/src/${partialName}.scss`,
        }
      }
      return null
    }
  ]
}),

And I get this error:

Cannot read property '$isServer' of undefined

Element UI Error

Hope anyone can help, thanks in advance.

Support mounting app via new Vue({el: "#app"})

Potentially to #34 (needs alias: { vue: require.resolve("vue/dist/vue.esm.js") })

Two ways to init (Vue 2):

// App.vue
const app = createApp({
  render: () => h(App),
});
// No App.vue — init on #app el
 var app = new Vue({
   el: "#app",
});

The latter will fail to register/find components.
If this is expected behavior, forgive me and close, but took me embarrassingly long to troubleshoot.

Hopefully this scenario can be supported. If a minimal codesandbox is needed, let me know.

ES Destructure import with customResolvers

I saw the new customResolvers feature, it's awesome

Is there a way that we can add a custom resolver for our ui-kit library? something like this:

{
  customResolvers: componentName => {
       return { path: 'bootstrap-vue', import: 'BSelect' }
  }
}

and import it like this:

import { BSelect } from 'bootstrap-vue' 

Thanks for the great work.

Error: Object.fromEntries is not a function

Hi, I'm new to Vite and I wanted to try it with this plugin, but when I import the plugin and use it in vite.config.js
I get the following error :
Capture d’écran 2021-04-14 à 12 59 09

I don't really know what I'm doing wrong because it's really the first thing i've done after starting the project.
Here is my vite.config.js

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import ViteComponents from 'vite-plugin-components'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    ViteComponents()
  ]
})

VuetifyResolver remove sass warnings

Hi 👋🏻

I'm not sure if this problem is related to vite-plugin-components or vuetify directly, but when I start the dev server of vite, I get this warning for each components of Vuetify:

   ╷
62 │     'sm': $grid-gutter / 6,
   │           ^^^^^^^^^^^^^^^^
   ╵
    node_modules/vuetify/src/styles/settings/_variables.scss 62:11     @import
    node_modules/vuetify/src/styles/settings/_index.sass 1:9           @import
    node_modules/vuetify/src/styles/styles.sass 2:9                    @import
    node_modules/vuetify/src/components/VTreeview/_variables.scss 1:9  @import
    node_modules/vuetify/src/components/VTreeview/VTreeview.sass 1:9   root stylesheet

DEPRECATION WARNING: Using / for division is deprecated and will be removed in Dart Sass 2.0.0.

Recommendation: math.div($grid-gutter, 3)

I find them annoying. Is there any way to hidde them or remove them?

SVGs as a component

Is this library can register SVGs as a component?

For example HomeIcon.svg will be used as <HomeIcon /> in template.

TypeError: Cannot read property 'endsWith' of undefined

I've added vite-plugin-components to my vite project and it simply throws an error saying:

[...]/node_modules/vite-plugin-components/dist/index.js:156
  return reqPath.endsWith(RESOLVER_EXT);
                 ^
TypeError: Cannot read property 'endsWith' of undefined

I've casually checked the source code and it seems koa.path is undefined.

Sourcemap is likely to be incorrect

When pack my project which use the plugin, the error shows as follow:

Sourcemap is likely to be incorrect: a plugin (vite-plugin-components) was used to transform files, but didn't generate a sourcemap for the transformation. Consult the plugin documentation for help

New components aren’t picked up automatically?

When I create a new component in src/components and right after reference it in another one, I get an error saying the component could not be resolved. I have to restart Vite for the component to be available.

Is this the desired behavior because of some limitations or am I doing something wrong?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.