• Stars
    star
    879
  • Rank 50,029 (Top 2 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created about 4 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Scan and auto import components for Nuxt.js 2.13+

@nuxt/components

@nuxt/components

npm version npm downloads Github Actions CI Codecov License

Module to scan and auto import components for Nuxt 2.13+

Table of Contents

Features

  • Automatically scan components/ 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 the components option in nuxt.config:

export default {
  components: true
}

Note: If using nuxt 2.10...2.13, you have to also manually install and add @nuxt/components to buildModules inside nuxt.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 the script section!

See live demo or video 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 with v-if or being in a modal

In order to lazy load a component, all we need to do is to add Lazy prefix to component name.

You now can easily import a component on-demand:

<template>
  <LazyComponentFoo v-if="foo" />
  <button @click="loadFoo">
    Load Foo
  </button>
</template>

<script>
  export default {
    data() {
      return {
        foo: null
      }
    },
    methods: {
      async loadFoo() {
        this.foo = await this.$axios.$get('foo')
      }
    }
  }
</script>

If you want to prefetch or preload the components with Lazy prefix, you can configure it by prefetch/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 use MyFormTextArea.vue as name with same directory structure.

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

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

Overwriting Components

It is possible to have a way to overwrite components using the level 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 the nuxt.config:

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

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

Directories

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

export default {
  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.js
export default {
  components: [{ path: '~/components', extensions: ['vue'] }]
}

pattern

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

Accept Pattern that will be run against specified path.

ignore

Ignore patterns that will be run against specified path.

prefix

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

Prefix all matched components.

Example below adds awesome-/Awesome prefix to the name of components in awesome/ directory.

// nuxt.config.js
export default {
  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 specified path for changes, including file additions and file deletions.

transpile

  • Type: Boolean
  • Default: 'auto'

Transpile specified path using build.transpile, by default ('auto') it will set transpile: true if node_modules/ is in path.

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.

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

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

prefetch/preload

  • Type: Boolean/Number
  • Default: false

These properties are used in production to configure how components with Lazy prefix are handled by Wepack via its magic comments, learn more in Wepack's official documentation.

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

yields:

// plugin.js
const componets = {
  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 using Lazy prefix or not.

Migration guide

v1 to v2

Starting with [email protected], Nuxt uses @nuxt/components v2:

  • All components are globally available so you can move components/global/ to components/ and global: true is not required anymore
  • Full path inside components is used to prefix component names. If you were structing your components in multiple directories, should either add prefix or register in components section of nuxt.config or use new pathPrefix option.

Example:

components
โ”œโ”€โ”€ atoms
โ”‚   โ””โ”€โ”€ icons
โ”œโ”€โ”€ molecules
โ”‚   โ””โ”€โ”€ illustrations
โ”œโ”€โ”€ organisms
โ”‚   โ””โ”€โ”€ ads
โ””โ”€โ”€ templates
    โ”œโ”€โ”€ blog
    โ””โ”€โ”€ home
// nuxt.config.js
export default {
  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 named components: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 in awesome-ui/nuxt.js you can use the components:dirs hook:

import { join } from 'path'

export default function() {
  this.nuxt.hook('components:dirs', dirs => {
    // Add ./components dir to the list
    dirs.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 your nuxt.config.js:

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

And directly use the module components (prefixed with awesome-), our pages/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 in node_modules/awesome-ui/components/.

Next: publish your awesome-ui module to npm and share it with the other Nuxters โœจ

License

MIT

More Repositories

1

nuxt

The Intuitive Vue Framework.
TypeScript
51,559
star
2

framework

Old repo of Nuxt 3 framework, now on nuxt/nuxt
10,721
star
3

awesome

A curated list of awesome things related to Nuxt.js
5,014
star
4

vue-meta

Manage HTML metadata in Vue.js components with SSR support
JavaScript
4,064
star
5

create-nuxt-app

Create Nuxt.js App in seconds.
JavaScript
3,451
star
6

ui

A UI Library for Modern Web Apps, powered by Vue & Tailwind CSS.
Vue
3,316
star
7

content

The file-based CMS for your Nuxt application, powered by Markdown and Vue components.
TypeScript
2,976
star
8

devtools

Unleash Nuxt Developer Experience
Vue
2,681
star
9

website-v2

Nuxt 2 Documentation Website
Vue
2,241
star
10

movies

๐Ÿฟ A TMDB client built with Nuxt 3
Vue
1,818
star
11

vite

โšก Vite Experience with Nuxt 2
TypeScript
1,385
star
12

image

Plug-and-play image optimization for Nuxt applications.
TypeScript
1,247
star
13

hackernews

HackerNews clone built with Nuxt.
Vue
1,197
star
14

modules

Discover the Nuxt modules to add any CMS, Database, UI, Auth and integrations into your Vue application.
TypeScript
871
star
15

example-auth0

A simple example that shows how to use Nuxt.js with Auth0.
Vue
713
star
16

vercel-builder

Vercel Builder for Nuxt
TypeScript
641
star
17

typescript

TypeScript Support for Nuxt 2
TypeScript
567
star
18

docs

Old Documentation of Nuxt.js ๐Ÿ’š - not in use anymore
539
star
19

learn.nuxt.com

[Work in Progress] An interactive tutorial and playground for Nuxt
Vue
492
star
20

starter

Create a new Nuxt project, module, layer or start from a theme with our collection of starters.
382
star
21

eslint-config

ESlint config used for Nuxt
JavaScript
346
star
22

fonts

Plug-and-play web font optimization and configuration for Nuxt apps.
TypeScript
345
star
23

test-utils

๐Ÿงช Test utilities for Nuxt
TypeScript
273
star
24

assets

๐ŸŽจ Unified Assets and Templates for Nuxt
HTML
267
star
25

bridge

๐ŸŒ‰ Experience Nuxt 3 features on existing Nuxt 2 projects
TypeScript
263
star
26

nuxt.com

The Nuxt website, made with Nuxt.
Vue
225
star
27

nuxt.new

Create a new Nuxt project from your address bar.
Vue
225
star
28

http

Universal HTTP Module for Nuxt.js
JavaScript
221
star
29

cli

โšก๏ธ Nuxt Generation CLI Experience.
TypeScript
207
star
30

module-builder

Complete solution to build Nuxt Modules.
TypeScript
202
star
31

nitro-demo

nuxt nitro preview
Vue
187
star
32

telemetry

Nuxt Telemetry
TypeScript
185
star
33

press

[Deprecated] Minimalist Markdown Publishing for Nuxt.js
JavaScript
184
star
34

todomvc

Nuxt.js TodoMVC Example
Vue
146
star
35

examples

Deployed Nuxt examples
TypeScript
134
star
36

eslint-plugin-nuxt

ESLint plugin for Nuxt.js [WIP]
JavaScript
129
star
37

nuxters

Vue
124
star
38

rfcs

RFCs for changes to Nuxt.js
97
star
39

loading-screen

Loading Screen Module for Nuxt.js
JavaScript
90
star
40

scripts

Plug-and-play script optimization for Nuxt applications. (Public Preview)
TypeScript
65
star
41

cli-draft

WIP: CLI for Nuxt.js projects
62
star
42

postcss8

Opt-in to postcss 8 in Nuxt 2 apps.
TypeScript
58
star
43

actions-yarn

Github Actions for yarn
Shell
47
star
44

codesandbox-nuxt

Starter template for CodeSandBox.io
Vue
43
star
45

blueprints

Module for Nuxt.js to create distributable micro-apps
JavaScript
41
star
46

benchmarks

๐Ÿ’จ Nuxt.js SSR performance Benchmarks
JavaScript
24
star
47

renovate-config-nuxt

Nuxt.js presets for Renovate tool.
18
star
48

nuxt-services-experimental

[WIP] Around realtime services for Nuxt 3
JavaScript
17
star
49

nuxt3-stubs

JavaScript
13
star
50

static

Fast Static Builder
TypeScript
12
star
51

governance

Nuxt Project Governance
12
star
52

babel-preset-app

PSA: this repo has been moved into nuxt.js/nuxt --> https://github.com/nuxt/nuxt.js/tree/dev/packages/babel-preset-app
JavaScript
10
star
53

nuxt-redirects

Nuxt.js redirects app for Netlify
9
star
54

.github

Default community health files for nuxt repositories
4
star