Как подключить css в nuxt.js?

Пользователь

от johnpaul.blick , в категории: JavaScript , год назад

Как подключить css в nuxt.js?

Facebook Vk Ok Twitter LinkedIn Telegram Whatsapp

2 ответа

Пользователь

от josie , год назад

@johnpaul.blick 

В Nuxt.js можно подключить CSS стили несколькими способами.

  1. Глобальный CSS файл:
  • Создайте файл global.css в директории assets вашего проекта
  • Откройте файл nuxt.config.js и добавьте следующий код:
1
2
3
4
5
export default {
  css: [
    '@/assets/global.css'
  ]
}


  1. CSS модули:
  • Создайте файл example.module.css в директории компонента components
  • В файле компонента импортируйте CSS модуль:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
<template>
  <div class="example">Example component</div>
</template>

<script>
import styles from '~/components/example.module.css'

export default {
  name: 'ExampleComponent',
  data() {
    return {
      styles
    }
  }
}
</script>

<style module>
.example {
  color: red;
}
</style>


  1. SCSS:
  • Установите node-sass и sass-loader пакеты командой npm install node-sass sass-loader --save-dev
  • Создайте файл example.scss в директории компонента components
  • В файле компонента импортируйте SCSS файл:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
<template>
  <div class="example">Example component</div>
</template>

<script>
import '~/components/example.scss'

export default {
  name: 'ExampleComponent'
}
</script>

<style lang="scss">
.example {
  color: red;
}
</style>


После этого, стили будут автоматически добавлены в проект.

Пользователь

от forest , 3 месяца назад

@johnpaul.blick 

Additional alternatives to importing CSS in Nuxt.js include:

  1. Inline styles: You can define CSS directly within the template using the style attribute.
1
2
3
<template>
  <div style="color: red;">Example component</div>
</template>


  1. CSS frameworks: If you are using a CSS framework like Tailwind CSS or Bootstrap, you can install the corresponding package and follow the documentation to import it into your project.
1
2
# Example for Tailwind CSS
npm install tailwindcss


Then, you can either import the CSS file globally in nuxt.config.js or directly into your components.

  1. Dedicated CSS files for each component: Instead of using CSS modules, you can create a separate CSS file for each component and import it directly into the component.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<template>
  <div class="example">Example component</div>
</template>

<script>
import '~/components/example.css'

export default {
  name: 'ExampleComponent'
}
</script>


Remember to include appropriate styles in the CSS file.


These methods offer flexibility in managing CSS styles depending on your project's requirements. Choose the best approach that suits your needs.