Vue js link css

Adding CSS to a Vue.js Project

This is part of a series of articles starting with “Working with CSS in Vue.js”. Focus in this article is on different ways of adding CSS to a Vue.js project.

Separate Global Style Files

If you prefer to keep your style files separate from the .vue files and their style tags, similar to a workflow without a framework, this can be achieved. Setting up the style files this way means the styling will be applied to your template sections, but not available in component style tags. Note: For example, if you create a SCSS variable in your style file, it will not be recognized if you try to use it within a component style tag. To get global styles available in component style tags, see the article about importing global styles in component style tags. Set up your folder and file structure for your style files, for example src/styles/style.scss. If you use a structure with folders, _filename.scss and SCSS imports, this will work provided you have added SCSS support. (See the article “Working with CSS in Vue.js” on adding SCSS support.) In your main.js file, import your styles below the Vue import:

Style Tags in Vue Files

The default version of handling CSS is to write your styles in the vue file style tags. Styles written in this way are global. Styles defined here are available in the project’s other .vue files.

Scoped Styletags

Scoping means adding data attributes to the different classes to keep them from leaking styles to one another. Scoping is similar to CSS Modules (read more about this in the article “CSS Modules in Vue.js”). Add “scoped” to the component style tag in the .vue file:

 scoped> /*add scoped styles here*/  

Style Cascading

If a child component has a class name that is shared by its parent component, the parent component style will cascade to the child. Read more about nesting with the deep selector in the documentation. To target children of scoped parents, use: .parent >>> child < /*styles*/ >Which syntax works depends on which preprocessor is used. Possible syntaxes are also: .parent /deep/ child < /*styles*/ >.parent ::v-deep child < /*styles*/ >Read more about this in the vue-loader documentation.

Setup

The starting code for this article is created by the Vue CLI command tool version 3.3.0 and Vue.js version 2.6.10. Note that both setup, plugins and framework are evolving. Changes will in time most certainly happen that make the techniques described in this post less relevant.

Читайте также:  Executing java programs on android

Источник

Working with CSS #

Vue CLI projects come with support for PostCSS, CSS Modules and pre-processors including Sass, Less and Stylus.

Referencing Assets #

All compiled CSS are processed by css-loader, which parses url() and resolves them as module requests. This means you can refer to assets using relative paths based on the local file structure. Note if you want to reference a file inside an npm dependency or via webpack alias, the path must be prefixed with ~ to avoid ambiguity. See Static Asset Handling for more details.

Pre-Processors #

You can select pre-processors (Sass/Less/Stylus) when creating the project. If you did not do so, the internal webpack config is still pre-configured to handle all of them. You just need to manually install the corresponding webpack loaders:

# Sass npm install -D sass-loader sass # Less npm install -D less-loader less # Stylus npm install -D stylus-loader stylus 

When using webpack version 4, the default in Vue CLI 4, you need to make sure your loaders are compatible with it. Otherwise you will get errors about confliciting peer dependencies. In this case you can use an older version of the loader that is still compatible with webpack 4.

# Sass npm install -D sass-loader@^10 sass 

Then you can import the corresponding file types, or use them in *.vue files with:

style lang="scss"> $color: red; style> 

A Tip on Sass Performance

Note that when using Dart Sass, synchronous compilation is twice as fast as asynchronous compilation by default, due to the overhead of asynchronous callbacks. To avoid this overhead, you can use the fibers package to call asynchronous importers from the synchronous code path. To enable this, simply install fibers as a project dependency:

Please also be aware, as it’s a native module, there may be compatibility issues vary on the OS and build environment. In that case, please run npm uninstall -D fibers to fix the problem.

Automatic imports #

If you want to automatically import files (for colors, variables, mixins. ), you can use the style-resources-loader. Here is an example for stylus that imports ./src/styles/imports.styl in every SFC and every stylus files:

// vue.config.js const path = require('path') module.exports =  chainWebpack: config =>  const types = ['vue-modules', 'vue', 'normal-modules', 'normal'] types.forEach(type => addStyleResource(config.module.rule('stylus').oneOf(type))) >, > function addStyleResource (rule)  rule.use('style-resource') .loader('style-resources-loader') .options( patterns: [ path.resolve(__dirname, './src/styles/imports.styl'), ], >) > 

PostCSS #

Vue CLI uses PostCSS internally.

You can configure PostCSS via .postcssrc or any config source supported by postcss-load-config, and configure postcss-loader via css.loaderOptions.postcss in vue.config.js .

The autoprefixer plugin is enabled by default. To configure the browser targets, use the browserslist field in package.json .

Note on Vendor-prefixed CSS Rules

In the production build, Vue CLI optimizes your CSS and will drop unnecessary vendor-prefixed CSS rules based on your browser targets. With autoprefixer enabled by default, you should always use only non-prefixed CSS rules.

CSS Modules #

To import CSS or other pre-processor files as CSS Modules in JavaScript, the filename should end with .module(s).(css|less|sass|scss|styl) :

import styles from './foo.module.css' // works for all supported pre-processors as well import sassStyles from './foo.module.scss' 

If you want to drop the .module in the file names and treat all style files as CSS Modules, you need to configure the css-loader option as follows:

// vue.config.js module.exports =  css:  loaderOptions:  css:  modules:  auto: () => true > > > > > 

If you wish to customize the generated CSS Modules class names, you can do so via css.loaderOptions.css in vue.config.js , too. All css-loader options are supported here:

// vue.config.js module.exports =  css:  loaderOptions:  css:  // Note: the following config format is different between different Vue CLI versions // See the corresponding css-loader documentation for more details. // Vue CLI v3 uses css-loader v1: https://www.npmjs.com/package/css-loader/v/1.0.1 // Vue CLI v4 uses css-loader v3: https://www.npmjs.com/package/css-loader/v/3.6.0 // Vue CLI v5 uses css-loader v5: https://github.com/webpack-contrib/css-loader#readme modules:  localIdentName: '[name]-[hash]' exportLocalsConvention: 'camelCaseOnly' > > > > > 

Passing Options to Pre-Processor Loaders #

Sometimes you may want to pass options to the pre-processor’s webpack loader. You can do that using the css.loaderOptions option in vue.config.js . For example, to pass some shared global variables to all your Sass/Less styles:

// vue.config.js module.exports =  css:  loaderOptions:  // pass options to sass-loader // @/ is an alias to src/ // so this assumes you have a file named `src/variables.sass` // Note: this option is named as "prependData" in sass-loader v8 sass:  additionalData: `@import "~@/variables.sass"` >, // by default the `sass` option will apply to both syntaxes // because `scss` syntax is also processed by sass-loader underlyingly // but when configuring the `prependData` option // `scss` syntax requires an semicolon at the end of a statement, while `sass` syntax requires none // in that case, we can target the `scss` syntax separately using the `scss` option scss:  additionalData: `@import "~@/variables.scss";` >, // pass Less.js Options to less-loader less: // http://lesscss.org/usage/#less-options-strict-units `Global Variables` // `primary` is global variables fields name globalVars:  primary: '#fff' > > > > > 

Loaders which can be configured via loaderOptions include:

This is preferred over manually tapping into specific loaders using chainWebpack , because these options need to be applied in multiple locations where the corresponding loader is used.

Источник

# Работа с CSS

, который будет парсить url() и разрешать их как зависимостями модуля. Это означает, что вы можете ссылаться на ресурсы, используя относительные пути на основе локальной файловой структуры. Обратите внимание, что если вы хотите ссылаться на файл внутри npm-зависимости или через псевдоним webpack, путь должен начинаться с префикса ~ для избежания двусмысленности. Подробнее в разделе Обработка статических ресурсов.

# Пре-процессоры

Вы можете выбрать пре-процессоры (Sass/Less/Stylus) при создании проекта. Если вы этого не сделали, то внутренняя конфигурация webpack всё равно настроена для их использования. Вам лишь требуется вручную доустановить соответствующие загрузчики для webpack:

# Sass npm install -D sass-loader node-sass # Less npm install -D less-loader less # Stylus npm install -D stylus-loader stylus 

Теперь вы можете импортировать соответствующие типы файлов, или использовать их синтаксис внутри файлов *.vue с помощью:

style lang="scss"> $color: red; style> 

# Автоматические импорты

Если вы хотите автоматически импортировать файлы (для цветов, переменных, примесей. ), можно использовать style-resources-loader

. Вот пример для stylus, который импортирует ./src/styles/imports.styl в каждый однофайловый компонент и в каждый файл stylus:

// vue.config.js const path = require('path') module.exports =  chainWebpack: config =>  const types = ['vue-modules', 'vue', 'normal-modules', 'normal'] types.forEach(type => addStyleResource(config.module.rule('stylus').oneOf(type))) >, > function addStyleResource (rule)  rule.use('style-resource') .loader('style-resources-loader') .options( patterns: [ path.resolve(__dirname, './src/styles/imports.styl'), ], >) > 

# PostCSS

Vue CLI использует PostCSS внутри себя.

Вы можете настроить PostCSS через .postcssrc или любую другую конфигурацию, которая поддерживается postcss-load-config

через опцию css.loaderOptions.postcss в файле vue.config.js .

включён по умолчанию. Чтобы определить целевые браузеры используйте поле browserslist в файле package.json .

Примечание о префиксных CSS правилах

В сборке для production Vue CLI оптимизирует ваш CSS и удаляет ненужные префиксные правила CSS, основываясь на целевых браузерах. С autoprefixer включённым по умолчанию, вы должны всегда использовать только CSS-правила без префиксов.

# CSS-модули

доступны из коробки с помощью .

Для импорта CSS или других файлов пре-процессоров в качестве CSS-модулей в JavaScript, необходимо чтобы имя файла заканчивалось на .module.(css|less|sass|scss|styl) :

import styles from './foo.module.css' // работает для всех поддерживаемых пре-процессоров import sassStyles from './foo.module.scss' 

Если вы не хотите указывать .module в именах файлов, установите css.modules в true внутри файла vue.config.js :

// vue.config.js module.exports =  css:  modules: true > > 

Если вы хотите настроить генерируемые имена классов для CSS-модулей, вы можете сделать это с помощью опции css.loaderOptions.css в vue.config.js . Все настройки css-loader поддерживаются, например localIdentName и camelCase :

// vue.config.js module.exports =  css:  loaderOptions:  css:  localIdentName: '[name]-[hash]', camelCase: 'only' > > > > 

# Передача настроек в загрузчики пре-процессоров

Иногда может возникнуть необходимость передать настройки в загрузчик пре-процессора для webpack. Вы можете сделать это с помощью опции css.loaderOptions в vue.config.js . Например, для передачи глобальных переменных во все стили Sass/Less:

// vue.config.js module.exports =  css:  loaderOptions:  // передача настроек в sass-loader sass:  // @/ это псевдоним к каталогу src/ поэтому предполагается, // что у вас в проекте есть файл `src/variables.scss` data: `@import "~@/variables.scss";` >, // передача настроек Less.js в less-loader less: // http://lesscss.org/usage/#less-options-strict-units `Global Variables` // `primary` — имя поля глобальных переменных globalVars:  primary: '#fff' > > > > > 

Загрузчики которые можно настраивать с помощью опции loaderOptions :

Это предпочтительнее, чем вручную обращаться к конкретным загрузчикам, используя chainWebpack , потому что настройки необходимо применять в нескольких местах, где используется соответствующий загрузчик.

Источник

Оцените статью