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: use unplugin for loader #235

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
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
38 changes: 0 additions & 38 deletions lib/installComponents.js

This file was deleted.

10 changes: 5 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@
"exports": {
".": "./dist/index.js",
"./*": "./*",
"./package.json": "./package.json",
"./loader": "./dist/loader.js"
"./package.json": "./package.json"
},
"main": "dist/index.js",
"types": "dist/index.d.ts",
Expand All @@ -27,14 +26,15 @@
"test": "yarn lint && jest --verbose"
},
"dependencies": {
"@rollup/pluginutils": "^4.1.1",
"chalk": "^4.1.2",
"chokidar": "^3.5.2",
"glob": "^7.1.7",
"globby": "^11.0.4",
"magic-string": "^0.25.7",
"pathe": "^0.2.0",
"scule": "^0.2.1",
"semver": "^7.3.5",
"upath": "^2.0.1",
"vue-template-compiler": "^2.6.14"
"unplugin": "^0.2.16"
},
"devDependencies": {
"@babel/preset-env": "latest",
Expand Down
54 changes: 20 additions & 34 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
import fs from 'fs'
import path from 'upath'
import { dirname, resolve, relative } from 'pathe'
import chokidar from 'chokidar'
import type { Configuration as WebpackConfig, Entry as WebpackEntry } from 'webpack'
import type { Module } from '@nuxt/types/config'
import consola from 'consola'

import { requireNuxtVersion } from './compatibility'
import { scanComponents } from './scan'
import type { Options, ComponentsDir } from './types'
import { loader } from './loader'

const isPureObjectOrString = (val: any) => (!Array.isArray(val) && typeof val === 'object') || typeof val === 'string'
const getDir = (p: string) => fs.statSync(p).isDirectory() ? p : path.dirname(p)
const getDir = (p: string) => fs.statSync(p).isDirectory() ? p : dirname(p)

const componentsModule: Module<Options> = function () {
const { nuxt } = this
Expand Down Expand Up @@ -46,7 +46,7 @@ const componentsModule: Module<Options> = function () {
}
} catch (err) {
/* istanbul ignore next */
nuxt.options.watch.push(path.resolve(nuxt.options.srcDir, 'components', 'global'))
nuxt.options.watch.push(resolve(nuxt.options.srcDir, 'components', 'global'))
}

const componentDirs = options.dirs.filter(isPureObjectOrString).map((dir) => {
Expand Down Expand Up @@ -98,36 +98,22 @@ const componentsModule: Module<Options> = function () {
consola.info('Using components loader to optimize imports')
this.extendBuild((config) => {
const vueRule = config.module?.rules.find(rule => rule.test?.toString().includes('.vue'))
if (!vueRule) {
throw new Error('Cannot find vue loader')
}
if (!vueRule.use) {
vueRule.use = [{
loader: vueRule.loader!.toString(),
options: vueRule.options
}]
delete vueRule.loader
delete vueRule.options
}
if (!Array.isArray(vueRule!.use)) {
// @ts-ignore
vueRule.use = [vueRule.use]
}

// @ts-ignore
vueRule!.use!.unshift({
loader: require.resolve('./loader'),
options: {
getComponents: () => components
config.plugins = config.plugins || []
config.plugins.push(loader.webpack({
include: vueRule?.test as any,
findComponent (name) {
return components.find(component => component.kebabName === name || component.pascalName === name)
}
})
}) as any)
})

// Add Webpack entry for runtime installComponents function
nuxt.hook('webpack:config', (configs: WebpackConfig[]) => {
for (const config of configs.filter(c => ['client', 'modern', 'server'].includes(c.name!))) {
((config.entry as WebpackEntry).app as string[]).unshift(path.resolve(__dirname, '../lib/installComponents.js'))
}
this.nuxt.hook('vite:extend', ({ config }: any) => {
config.plugins = config.plugins || []
config.plugins.push(loader.vite({
findComponent (name) {
return components.find(component => component.kebabName === name || component.pascalName === name)
}
}))
})
}

Expand Down Expand Up @@ -164,16 +150,16 @@ const componentsModule: Module<Options> = function () {
]
for (const t of templates) {
this[t.includes('plugin') ? 'addPlugin' : 'addTemplate']({
src: path.resolve(__dirname, '../templates', t),
src: resolve(__dirname, '../templates', t),
fileName: t.replace('_', '.'),
options: { getComponents }
})
}

// Add CLI info to inspect discovered components
const componentsListFile = path.resolve(nuxt.options.buildDir, 'components/readme.md')
const componentsListFile = resolve(nuxt.options.buildDir, 'components/readme.md')
// eslint-disable-next-line no-console
consola.info('Discovered Components:', path.relative(process.cwd(), componentsListFile))
consola.info('Discovered Components:', relative(process.cwd(), componentsListFile))
})
}

Expand Down
97 changes: 64 additions & 33 deletions src/loader.ts
Original file line number Diff line number Diff line change
@@ -1,42 +1,73 @@
import type { loader as WebpackLoader } from 'webpack'
import { extractTags } from './tagExtractor'
import { matcher } from './scan'
import type { Component } from './types'

function install (this: WebpackLoader.LoaderContext, content: string, components: Component[]) {
const imports = '{' + components.map(c => `${c.pascalName}: ${c.isAsync ? c.asyncImport : c.import}`).join(',') + '}'

let newContent = '/* nuxt-component-imports */\n'
newContent += `installComponents(component, ${imports})\n`

// Insert our modification before the HMR code
const hotReload = content.indexOf('/* hot reload */')
if (hotReload > -1) {
content = content.slice(0, hotReload) + newContent + '\n\n' + content.slice(hotReload)
} else {
content += '\n\n' + newContent
}
import { createUnplugin } from 'unplugin'
import MagicString from 'magic-string'
import { pascalCase } from 'scule'
import { createFilter } from '@rollup/pluginutils'
import type { FilterPattern } from '@rollup/pluginutils'
import { Component } from './types'

export const DISABLE_COMMENT = '/* nuxt-components disabled */'

return content
export interface Options {
findComponent(name: string): Component | void | Promise<Component | void>
include?: FilterPattern
exclude?: FilterPattern
}

export default async function loader (this: WebpackLoader.LoaderContext, content: string) {
this.async()
this.cacheable()
export const loader = createUnplugin<Options>((options) => {
const filter = createFilter(
options?.include || [/\.vue$/, /\.vue\?vue/],
options?.exclude || [/node_modules/, /\.git/, /\.nuxt/]
)

return {
name: 'nuxt-components-loader',
enforce: 'post',

transformInclude (id) {
return filter(id)
},

async transform (code, id) {
if (code.includes(DISABLE_COMMENT)) {
return
}

if (!this.resourceQuery) {
this.addDependency(this.resourcePath)
const s = new MagicString(code)

const { getComponents } = this.query
const nonAsyncComponents = getComponents().filter((c: Component) => c.isAsync !== true)
let no = 0
const componentPaths: string[] = []
const prepend: string[] = []

const tags = await extractTags(this.resourcePath)
const matchedComponents = matcher(tags, nonAsyncComponents)
for (const match of code.matchAll(/_c\([\s\n\t]*['"](.+?)["']([,)])/g)) {
const [full, matchedName, append] = match

if (matchedComponents.length) {
content = install.call(this, content, matchedComponents)
if (match.index != null && matchedName && !matchedName.startsWith('_')) {
const start = match.index
const end = start + full.length
const name = pascalCase(matchedName)
componentPaths.push(name)
const component = await options!.findComponent(name)
if (component && !id.startsWith(component.filePath)) {
const varName = `__nuxt_components_${no}`
prepend.push(`import ${varName} from "${component.filePath}"`)
no += 1
s.overwrite(start, end, `_c(${varName}${append}`)
}
}
}

if (!prepend.length) {
return null
}

s.prepend(`${DISABLE_COMMENT}${prepend.join(';')};`)
return {
code: s.toString(),
map: s.generateMap({
source: id,
includeContent: true
})
}
}
}

this.callback(null, content)
}
})
2 changes: 1 addition & 1 deletion src/scan.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { basename, extname, join, dirname, relative } from 'upath'
import { basename, extname, join, dirname, relative } from 'pathe'
import globby from 'globby'
import { pascalCase, splitByCase } from 'scule'
import type { ScanDir, Component } from './types'
Expand Down
31 changes: 0 additions & 31 deletions src/tagExtractor.ts

This file was deleted.

8 changes: 8 additions & 0 deletions test/unit/__snapshots__/loader.test.ts.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`loader 1`] = `
"/* nuxt-components disabled */import __nuxt_components_0 from \\"/Users/antfu/i/nuxt-components/test/fixture/components/Header.vue\\";import __nuxt_components_1 from \\"/Users/antfu/i/nuxt-components/test/fixture/components/Foo.vue\\";import __nuxt_components_2 from \\"/Users/antfu/i/nuxt-components/test/fixture/components/0-base/1.Button.vue\\";import __nuxt_components_3 from \\"/Users/antfu/i/nuxt-components/test/fixture/components/icons/Home.vue\\";import __nuxt_components_4 from \\"/Users/antfu/i/nuxt-components/test/fixture/components/functional/Functional.vue\\";import __nuxt_components_5 from \\"/Users/antfu/i/nuxt-components/test/fixture/components/NComponent.vue\\";function anonymous(
) {
with(this){return _c('div',[_c(__nuxt_components_0),_v(\\" \\"),_c(__nuxt_components_1),_v(\\" \\"),_c('LazyBar'),_v(\\" \\"),_c(__nuxt_components_2),_v(\\" \\"),_c(__nuxt_components_3),_v(\\" \\"),_c('MAwesome'),_v(\\" \\"),_c(__nuxt_components_4),_v(\\" \\"),_c(__nuxt_components_5)],1)}
}"
`;
Loading