Frameworks like Vue.js offer many different ways of adding CSS to a web project. Compared to working without a framework, the framework build process is however often more complex.
This is the first part in a series of articles about working with CSS in Vue.js. The article is meant as a resource when it comes to the different ways of handling CSS in Vue.js. Main topics in this article are how to add preprocessors, autoprefixing and source maps.
Note that for production, Vue.js creates a separate css file that is linked in the document head. Read more about the Vue.js build process here.
Start Setup
The starting code for this article is created by the Vue CLI command tool v3.3.0. Run vue --version
in the command prompt to see the version number. The Vue version is v.2.6.10. Run npm list vue
in the command prompt to see the Vue version.
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.
Adding SASS/SCSS to Vue.js
To add support for sass/scss, install sass-loader as a development dependency in the project folder by running: npm install --save-dev sass-loader
in the command prompt.
Since sass-loader depends on node-sass, you will have to install that as well, by running: npm install --save-dev node-sass
Declare the language on styletags in .vue files: <style lang=”scss”>
Autoprefixing
Settings for autoprefixing can be found in package.json, provided you have chosen to use a package.json file when creating the project with Vue CLI. Read more about how to configure the browserlist settings.
CSS Source Maps
Add source maps by adding the following to the vue.config.js file. If the vue.config.js file hasn’t yet been created, you can create one and save it directly in the project folder.
/* vue.config.js */
module.exports = {
css: {
sourceMap: true
}
}
Separate CSS file
A separate CSS file will be created when the project is built for production, and linked in the document head.
There is a setting in the vue.config.js file to also get a separate CSS file linked to the document head during development:
/* vue.config.js */
module.exports = {
css: {
extract: true
}
}
It is set to false per default because setting it to true will interfere with hot module reloading. It is possible to set it to true, but then hot module reloading will not work.
Setting it to true during development also means source maps will point to the compiled CSS file, and not to the real individual sources. If you need more control over the code splitting, Vue docs points to a plugin: mini-css-extract-plugin.
Read more about the extract
setting in the official Vue documents, as well as the official instructions about deployment.
Top comments (0)