• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

Building a Nuxt module from scratch

Lomanu4 Оффлайн

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
1,481
Баллы
155
Nuxt 3, the latest evolution of the popular Vue framework, offers powerful extensibility through modules. Modules are the cornerstone of reusable logic in Nuxt, allowing developers to encapsulate functionality and plug it into projects with ease.

In this article, we’ll walk through creating a Nuxt module from scratch, step-by-step—from scaffolding to publishig.

Enjoy!

? What Is a Nuxt Module?


A Nuxt module is a function that can extend the core functionality of a Nuxt application. Modules can:

  • Add runtime or build-time features
  • Modify the Nuxt configuration
  • Register components, plugins, routes, and more

Nuxt’s architecture makes writing and using modules seamless.

? Building a Nuxt module


We'll use the official

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

to scaffold our module project quickly.


npx nuxi init my-nuxt-module
cd my-nuxt-module

This will generate the initial folder structure with everything you need to get started. Now, let's install the project dependencies:


pnpm install

Or use yarn or npm depending on your preference. After scaffolding, you'll see:


my-nuxt-module/
├── src/
│ └── module.ts
├── playground/
├── package.json
├── tsconfig.json
└── README.md
  • src/module.ts: This is the entry point for your module logic.
  • playground/: A Nuxt 3 app to test your module locally.
  • package.json: Metadata and configuration for your module.

To write the module logic, open src/module.ts. Here's a basic example:


import { defineNuxtModule } from '@nuxt/kit'

export default defineNuxtModule({
meta: {
name: 'my-nuxt-module',
configKey: 'myModule',
},
defaults: {
greeting: 'Hello from My Module!',
},
setup(options, nuxt) {
nuxt.hook('ready', () => {
console.log(options.greeting)
})
}
})
  • meta: Provides information about your module.
  • defaults: Default options that users can override.
  • setup: Main logic, where you can hook into Nuxt lifecycle events.

To test our module, use the included playground/ app to test your module.


// playground/nuxt.config.ts

export default defineNuxtConfig({
modules: ['../src/module'],
myModule: {
greeting: 'Hello from Playground!'
}
})

Run the playground:


pnpm dev

You should see the custom greeting in your terminal.

To learn more about what you can do as a part of the module logic, check out the official documentation

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

.

To publish the module we would need to follow these steps:

Step 1: Build


pnpm build

Step 2: Prepare for NPM

Ensure your package.json has the right metadata:


{
"name": "my-nuxt-module",
"version": "1.0.0",
"main": "./dist/module.mjs",
"exports": {
".": {
"import": "./dist/module.mjs"
}
},
"files": ["dist"]
}

Step 3: Publish


npm publish --access public

And that's it! Our module is in NPM available for other developers to download and use in their projects.

? Learn more


If you would like to learn more about Vue, Nuxt, JavaScript or other useful technologies, checkout VueSchool by clicking this

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

or by clicking the image below:


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.



It covers most important concepts while building modern Vue or Nuxt applications that can help you in your daily work or side projects ?

✅ Summary


Building a Nuxt module is not only straightforward but also incredibly powerful. By modularizing your logic, you can create reusable, clean, and maintainable code across multiple Nuxt projects.

Take care and see you next time!

And happy coding as always ?️


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу