Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Scan and auto import components for Nuxt.js 2.13+

License

NotificationsYou must be signed in to change notification settings

nuxt/components

@nuxt/components

@nuxt/components

npm versionnpm downloadsGithub Actions CICodecovLicense

Module to scan and auto import components for Nuxt 2.13+

Table of Contents

Features

  • Automatically scancomponents/ directory
  • No need to manually import components anymore
  • Multiple paths with customizable prefixes and lookup/ignore patterns
  • Lazy loading (Async components)
  • Production code-splitting optimization (loader)
  • Hot reloading
  • Module integration (library authors)
  • Fully tested

Usage

Set thecomponents option innuxt.config:

exportdefault{components:true}

Note: If using nuxt2.10...2.13, you have to also manually install and add@nuxt/components tobuildModules insidenuxt.config.

Create your components:

| components/---| ComponentFoo.vue---| ComponentBar.vue

Use them whenever you want, they will be auto imported in.vue files :

<template><ComponentFoo/><component-bar/></template>

No need anymore to manually import them in thescript section!

Seelive demo orvideo example.

Lazy Imports

Nuxt by default does code-splitting per page and components. But sometimes we also need to lazy load them:

  • Component size is rather big (or has big dependencies imported) like a text-editor
  • Component is rendered conditionally withv-if or being in a modal

In order tolazy load a component, all we need to do is to addLazy prefix to component name.

You now can easily import a component on-demand:

<template><LazyComponentFoov-if="foo"/><button@click="loadFoo">    Load Foo</button></template><script>exportdefault{data(){return{foo:null}},methods:{asyncloadFoo(){this.foo=awaitthis.$axios.$get('foo')}}}</script>

If you want to prefetch or preload the components withLazy prefix, you can configure it byprefetch/preload options.

Nested Components

If you have components in nested directories:

| components/---| my/------| form/---------| TextArea.vue

The component name will contain its path:

<MyFormTextArea/>

For clarity, it is recommended that component file name matches its name. You can also useMyFormTextArea.vue as name with same directory structure.

If for any reason different prefix is desired, we can add specific directory with theprefix option: (Seedirectories section)

components:['~/components/',{path:'~/components/foo/',prefix:'foo'}]

Overwriting Components

It is possible to have a way to overwrite components using thelevel option. This is very useful for modules and theme authors.

Considering this structure:

| node_modules/---| my-theme/------| components/---------| Header.vue| components/---| Header.vue

Then defining in thenuxt.config:

components:['~/components',// default level is 0{path:'node_modules/my-theme/components',level:1}]

Ourcomponents/Header.vue will overwrite our theme component since the lowest level overwrites.

Directories

By settingcomponents: true, default~/components directory will be included.However you can customize module behaviour by providing directories to scan:

exportdefault{components:['~/components',// shortcut to { path: '~/components' }{path:'~/components/awesome/',prefix:'awesome'}]}

Each item can be either string or object. String is shortcut to{ path }.

Note: Don't worry about ordering or overlapping directories! Components module will take care of it. Each file will be only matched once with longest path.

Directory Properties

path

  • Required
  • Type:String

Path (absolute or relative) to the directory containing your components.

You can use Nuxt aliases (~ or@) to refer to directories inside project or directly use a npm package path similar to require.

extensions

  • Type:Array<string>
  • Default:
    • Extensions supported by Nuxt builder (builder.supportedExtensions)
    • Default supported extensions['vue', 'js'] or['vue', 'js', 'ts', 'tsx'] depending on your environment

Example: Support multi-file component structure

If you prefer to split your SFCs into.js,.vue and.css, you can only enable.vue files to be scanned:

| components---| componentC------| componentC.vue------| componentC.js------| componentC.scss
// nuxt.config.jsexportdefault{components:[{path:'~/components',extensions:['vue']}]}

pattern

  • Type:string (glob pattern)
  • Default:**/*.${extensions.join(',')}

Accept Pattern that will be run against specifiedpath.

ignore

Ignore patterns that will be run against specifiedpath.

prefix

  • Type:String
  • Default:'' (no prefix)

Prefix all matched components.

Example below addsawesome-/Awesome prefix to the name of components inawesome/ directory.

// nuxt.config.jsexportdefault{components:['~/components',{path:'~/components/awesome/',prefix:'awesome'}]}
components/  awesome/    Button.vue  Button.vue
<template><div><AwesomeButton>Click on me 🤘</AwesomeButton><button>Click on me</button></div></template>

pathPrefix

  • Type:Boolean
  • Default:true

Prefix component name by it's path

watch

  • Type:Boolean
  • Default:true

Watch specifiedpath for changes, including file additions and file deletions.

transpile

  • Type:Boolean
  • Default:'auto'

Transpile specifiedpath usingbuild.transpile, by default ('auto') it will settranspile: true ifnode_modules/ is inpath.

level

  • Type:Number
  • Default:0

Level are use to define a hint when overwriting the components which have the same name in two different directories, this is useful for theming.

exportdefault{components:['~/components',// default level is 0{path:'my-theme/components',level:1}]}

Components having the same name in~/components will overwrite the one inmy-theme/components, learn more inOverwriting Components. The lowest value will overwrite.

prefetch/preload

  • Type:Boolean/Number
  • Default:false

These properties are used in production to configure howcomponents withLazy prefix are handled by Wepack via its magic comments, learn more inWepack's official documentation.

exportdefault{components:[{path:'my-theme/components',prefetch:true}]}

yields:

// plugin.jsconstcomponets={MyComponentA:import(/* webpackPrefetch: true */ ...),MyComponentB:import(/* webpackPrefetch: true */ ...)}

isAsync

  • Type: Boolean
  • Default:false unless component name ends with.async.vue

This flag indicates, component should be loaded async (with a seperate chunk) regardless of usingLazy prefix or not.

Migration guide

v1 tov2

Starting withnuxt@2.15, Nuxt uses@nuxt/components v2:

  • All components are globally available so you can movecomponents/global/tocomponents/ andglobal: true is not required anymore
  • Full path insidecomponents is used to prefix component names. If you were structing yourcomponents in multiple directories, should either add prefix or register incomponents section ofnuxt.config or use newpathPrefix option.

Example:

components├── atoms│   └── icons├── molecules│   └── illustrations├── organisms│   └── ads└── templates    ├── blog    └── home
// nuxt.config.jsexportdefault{components:['~/components/templates','~/components/atoms','~/components/molecules','~/components/organisms']}

Library Authors

Making Vue Component libraries with automatic tree-shaking and component registration is now damn easy ✨

This module expose a hook namedcomponents:dirs so you can easily extend the directory list without updating user configuration in your Nuxt module.

Imagine a directory structure like this:

| node_modules/---| awesome-ui/------| components/---------| Alert.vue---------| Button.vue------| nuxt.js| pages/---| index.vue| nuxt.config.js

Then inawesome-ui/nuxt.js you can use thecomponents:dirs hook:

import{join}from'path'exportdefaultfunction(){this.nuxt.hook('components:dirs',dirs=>{// Add ./components dir to the listdirs.push({path:join(__dirname,'components'),prefix:'awesome'})})}

That's it! Now in your project, you can import your ui library as a Nuxt module in yournuxt.config.js:

exportdefault{buildModules:['@nuxt/components','awesome-ui/nuxt']}

And directly use the module components (prefixed withawesome-), ourpages/index.vue:

<template>  <div>    My <AwesomeButton>UI button</AwesomeButton>!    <awesome-alert>Here's an alert!</awesome-alert>  </div></template>

It will automatically import the components only if used and also support HMR when updating your components innode_modules/awesome-ui/components/.

Next: publish yourawesome-ui module tonpm and share it with the other Nuxters ✨

License

MIT

About

Scan and auto import components for Nuxt.js 2.13+

Topics

Resources

License

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Sponsor this project

 

Packages

No packages published

Contributors27


[8]ページ先頭

©2009-2025 Movatter.jp