Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support @nuxt/components auto-import #63

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion examples/nuxt/nuxt.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ export default {
buildModules: [
['@nuxt/typescript-build', { typeCheck: false }],
'@nuxtjs/composition-api/module',
'unplugin-vue2-script-setup/nuxt',
'unplugin-icons/nuxt',
],
components: true,
}
3 changes: 1 addition & 2 deletions examples/nuxt/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
"@nuxt/typescript-build": "^2.1.0",
"@nuxtjs/composition-api": "^0.29.0",
"css-loader": "^5.2.0",
"unplugin-icons": "workspace:*",
"unplugin-vue2-script-setup": "^0.6.1"
"unplugin-icons": "workspace:*"
}
}
6 changes: 2 additions & 4 deletions examples/nuxt/pages/index.vue
Original file line number Diff line number Diff line change
@@ -1,18 +1,16 @@
<template>
<div class="markdown-body" style="padding: 2em 3em">
<logo-nuxt style="font-size:2em" />
<i-logos-nuxt-icon style="font-size:2em" />
<br>
<p>
Icons
<MdiStore24Hour />
<IMdiStore24Hour />
<MdiAlarmOff />
from <code>unplugin-icons</code>
</p>
</div>
</template>

<script setup>
import LogoNuxt from '~icons/logos/nuxt-icon'
import MdiStore24Hour from '~icons/mdi/store-24-hour'
import MdiAlarmOff from '~icons/mdi/alarm-off'
</script>
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@
"dependencies": {
"@antfu/utils": "^0.3.0",
"@iconify/json-tools": "^1.0.10",
"fast-glob": "^3.2.7",
"has-pkg": "^0.0.1",
"unplugin": "^0.2.9"
},
Expand Down
11 changes: 5 additions & 6 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

84 changes: 83 additions & 1 deletion src/nuxt.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,37 @@
import { promises as fs } from 'fs'
import fg from 'fast-glob'
import { Options } from './types'
import IconResolver, { ComponentResolverOptions } from './resolver'
import { pascalize } from './core/utils'
import unplugin from '.'

export default function(this: any, options: Options) {
export interface Component {
pascalName: string
kebabName: string
import: string
asyncImport: string
export: string
filePath: string
shortPath: string
isAsync?: boolean
chunkName: string
level: number
prefetch: boolean
preload: boolean

// await for https://github.com/nuxt/components/pull/234
isAbsolute: boolean
}

function hyphenate(str: string): string {
return str.replace(/\B([A-Z])/g, '-$1').toLowerCase()
}

interface NuxtOptions extends Options {
resolver?: ComponentResolverOptions
}

export default function(this: any, options: NuxtOptions) {
// install webpack plugin
this.extendBuild((config: any) => {
config.plugins = config.plugins || []
Expand All @@ -13,4 +43,56 @@ export default function(this: any, options: Options) {
vite.config.plugins = vite.config.plugins || []
vite.config.plugins.push(unplugin.vite(options))
})

if (this.nuxt.options.components === false)
return

// Auto import for components
const resolver = IconResolver(options.resolver)
this.nuxt.hook('components:extend', async(components: Component[]) => {
const files = await fg(['**/*.vue'], {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Components module is supposed to to glob on added directories. Why are you doing it manually? 🙈

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In https://github.com/antfu/unplugin-vue-components we are scanning for components usages on each request, meaning that if you use a component like this:

// pages/index.vue
<template>
  <mdi-alarm />
</template>

In that case, we will know that the Alarm icon from MDI is used, and inject the import statement to it. While with @nuxt/components, we need to search for the components usage beforehand as we register them globally on dev. This is indeed an workaround, but do you see any better solution for that?

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hook is components:dirs

components:extend was mainly added to fine-tune scanned components (IE if generated names need a change) and also exposing multiple components from same export (which i guess you have 1 file per component)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For what I need is kinda another way around, I need to scan the usage of the components used instead of the components to be imported. components:dirs might not work for me as the icons aren't actually exist in the filesystem.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In that case, we will know that the Alarm icon from MDI is used, and inject the import statement to it. While with @nuxt/components, we need to search for the components usage beforehand as we register them globally on dev. This is indeed a workaround, but do you see any better solution for that?

It is the same for nuxt build. Loader that scans usage is intentionally disabled on development as the cost of this scanning step was proven to be more and not scalable as the number of .vue files and components increases. One can force this behavior in dev by setting loader: true in the components option.

Can't we simply register all unplugin-vue components beforehand to Components module and let it lazy-load them in dev with isAsync: true ?

Copy link

@pi0 pi0 Sep 15, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Another point: There is runtime usage where the scanner cannot basically detect them by usage. Markdown (docus/content) is one example that is rendered after build step :)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can't we simply register all unplugin-vue components beforehand to Components module and let it lazy-load them in dev with isAsync: true ?

While in this case, Iconify has 10,000+ icons from over 100 icon sets. We certainly don't want to register them all 😅 and that's why we go with this on-demand approach.

Loader

Yes, this is indeed we are doing the same thing with the loader and I understand the tradeoff in dev here. If you don't mind to have an additional hook in the loader, we could have the on-demand resolution for loader, and fallback to this solution when the loader is not enabled.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Enabling loader if one of dirs requires it, would be nice idea indeed :) Would you please make an Issue+PR?

onlyFiles: true,
cwd: this.options.rootDir,
absolute: true,
ignore: ['node_modules', '.git', 'dist', '.nuxt', '.output'],
})

const tags = new Set<string>()
const tagRE = /<([a-zA-Z0-9-]+)\s/g

await Promise.all(files.map(async(file) => {
const content = await fs.readFile(file, 'utf-8')
let m
tagRE.lastIndex = 0
do {
m = tagRE.exec(content)
if (m && m[1])
tags.add(pascalize(m[1]))
} while (m)
}))

Array.from(tags)
.filter(tag => !components.find(i => i.pascalName === tag || i.kebabName === tag))
.forEach((tag) => {
const result = resolver(tag)
if (result) {
const kebabName = hyphenate(tag)
components.push({
pascalName: tag,
kebabName,
chunkName: `~icons/${kebabName}`,
isAsync: false,
import: `require('${result}').default`,
filePath: result,
shortPath: result,
asyncImport: `function () { return import('${result}' /* webpackChunkName: "~icons/${kebabName}" */).then(function(m) { return m['default'] || m }) }`,
export: 'default',
level: 0,
prefetch: false,
preload: false,
isAbsolute: true,
})
}
})
})
}
4 changes: 2 additions & 2 deletions src/resolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import Data from '@iconify/json'
import { getBuiltinIcon } from './core/loader'
import { camelToKebab } from './core/utils'

export interface ComponentResolverOption {
export interface ComponentResolverOptions {
/**
* Prefix for resolving components name.
* Set '' to disable prefix.
Expand Down Expand Up @@ -44,7 +44,7 @@ export interface ComponentResolverOption {
*
* @param options
*/
export default function ComponentsResolver(options: ComponentResolverOption = {}) {
export default function ComponentsResolver(options: ComponentResolverOptions = {}) {
const {
prefix: rawPrefix = options.componentPrefix ?? 'i',
enabledCollections = Object.keys(Data.collections()),
Expand Down