how to use sass using in vuejs3/vite - vuejs3

I starting with vite / vuejs 3
after installing sass with npm install -D sass I tried to add my _variables.js file this to vite.config.js
css: {preprocessorOptions: {scss: {additionalData: `#import" ./src/css/_variables.scss ";`,},},},
din't work!
it also worked in vue.config
css: {
loaderOptions: {
sass: {
sassOptions: {
prependData: `#import" # / css / _variables.scss ";`,
}
}
}
},
after this tried to import the file in main.js import "./css/_variables.scss"
Unfortunately, my components cannot find the variables, where is the error

Vite is a litte bit different
import { defineConfig } from 'vite'
export default defineConfig({
css: {
preprocessorOptions: {
scss: {
additionalData: `
#import "./src/styles/_animations.scss";
#import "./src/styles/_variables.scss";
#import "./src/styles/_mixins.scss";
#import "./src/styles/_helpers.scss";
`
}
}
}
})

here is my working setup, got it from the vite docs and with the command yarn add -D sass
// package.json
{
"dependencies": {
...
"vue": "^3.0.5"
},
"devDependencies": {
...
"sass": "^1.32.11",
"vite": "^2.2.3"
}
}
// vite.config.js
import { defineConfig } from 'vite'
import vue from '#vitejs/plugin-vue'
export default defineConfig({
plugins: [vue()]
})
// App.vue
<template>...</template>
<script>...</script>
<style lang="scss">
#import "./assets/style.scss";
</style>
// style.scss
[data-theme="dark"] {
--bg-color1: #121416;
--font-color: #f4f4f4;
}
[data-theme="light"] {
--bg-color1: #f4f4f4;
--font-color: #121416;
}
...
body {
background-color: var(--bg-color1);
color: var(--font-color);
}
and my vue.config.js is clean - nothing fancy there.

For Vue3, as stated in the documentation: https://vitejs.dev/guide/features.html#css-pre-processors
You only need to add
npm add -D sass
And in the script tag use
<style lang="scss">
// OR
<style lang="sass">

My problem was the following: I coudn't get scss variables within <style lang="scss"> and now this is my good config:
// vite.config.ts
export default defineConfig({
plugins: [
vue(),
...
],
...,
css: {
preprocessorOptions: {
scss: {
additionalData: ` // just variables loaded globally
#import "./src/assets/styles/setup/fonts";
#import "./src/assets/styles/setup/colors";
#import "./src/assets/styles/setup/mixins";
`
}
}
}
});
// App.vue
<style lang="scss"> // the main file that imports everything related with styles
#import "#/assets/styles/main.scss";
</style>

I had the same problem and simply solved it by installing sass as a Dev dependency.
npm i -D sass

Solutions:
"npm add -D sass" ---------- (-g flag will not work in vite now 16/02/2022).
Or,
"yarn add -D sass" - Run these comments in your command line.
In main.js file "import './style.scss' " will not work, so I added my sass file in html

If already install sass in your react.js app. Uninstall it.
Once Uninstall is done Check your packge.json file. It's will look like that.
"devDependencies": {
"#types/react": "^18.0.17",
"#types/react-dom": "^18.0.6",
"#vitejs/plugin-react": "^2.1.0",
"vite": "^3.1.0" }
Then Ren this command
npm cache clean --force or npm cache clean -f
Close your Vscode and Re-open it.
Now Reinstall sass in your react vite app.
# .scss and .sass
npm add -D sass
# .less
npm add -D less
# .styl and .stylus
npm add -D stylus
Once Installation done your json file look like that.
"devDependencies": {
"#types/react": "^18.0.17",
"#types/react-dom": "^18.0.6",
"#vitejs/plugin-react": "^2.1.0",
"sass": "^1.55.0",
"vite": "^3.1.0"
}

Related

Mixin partial and variables partial not detected when scss is compiled. Error: Undefined Mixin and Partial

My _variables.scss and _mixins.scss partials do not seem to be picked up when I compile my Sass files. My _globals.scss and _header.scss are picked up fine, even though they are in the same directory and accessed the same way.
In my style.scss file:
#use "globals";
#use "header";
Terminal error messages:
Error: Undefined mixin.
#include breakpoint-down(medium){display: none;}
Error: Undefined variable.
color: $grayishBlue;
I used a package.json code to compile my sass, with a few tweaks. Here is what mine looks like:
{
"name": "project",
"version": "0.1.0",
"description": "SASS compile|autoprefix|minimize and live-reload dev server using Browsersync for static HTML",
"main": "public/index.html",
"author": "5t3ph",
"scripts": {
"build:sass": "sass --no-source-map src/sass:public/css",
"copy:images": "copyfiles -u 1 ./src/images/**/* public",
"copy:html": "copyfiles -u 1 ./src/*.html public",
"copy": "npm-run-all --parallel copy:*",
"watch:images": "onchange 'src/images/**/*' -- npm run copy:html",
"watch:html": "onchange 'src/*.html' -- npm run copy:html",
"watch:sass": "sass --no-source-map --watch src/sass:public/css",
"watch": "npm-run-all --parallel watch:*",
"serve": "browser-sync start --server public --files public",
"start": "npm-run-all copy --parallel watch serve",
"build": "npm-run-all copy:html build:*",
"postbuild": "postcss public/css/*.css -u autoprefixer cssnano -r --no-map"
},
"dependencies": {
"autoprefixer": "^10.4.2",
"browser-sync": "^2.27.7",
"copyfiles": "^2.4.1",
"cssnano": "^5.0.17",
"npm-run-all": "^4.1.5",
"onchange": "^7.1.0",
"postcss-cli": "^9.1.0",
"sass": "^1.49.8"
}
}
_globals.scss file:
#use "variables";
#use "mixins";
html {
font-size: 100%;
box-sizing: border-box;
}
*, *::before, *::after {
box-sizing: inherit;
}
body {
margin: 0;
padding: 0;
font-family: 'Public Sans', sans-serif;
font-size: 1.125rem;
font-weight: 300;
color: $grayishBlue; //if i comment out this line, i get an error //for mixins.
line-height: 1.3;
}
// and so on... until we get to the styles that use the mixin.
//Visibility
.hide-for-mobile {
// hide for mobile and tablet
#include breakpoint-down(medium){
display: none;
}
}
.hide-for-desktop {
//hide for desktop viewport widths
#include breakpoint-up(large){
display: none;
}
}
_header.scss file:
#use "variables";
.header {
nav {
padding: 24px;
}
//and so on... variables are used twice in this module.
File hierarchy in the sass folder is as follows:
- sass
- _globals.scss
- _header.scss
- _mixins.scss
- _variables.scss
- style.css
- style.css.map
- style.scss
As stated in the doc:
Members (variables, functions, and mixins) loaded with #use are only visible in the stylesheet that loads them. Other stylesheets will need to write their own #use rules if they also want to access them.
Which means that in order to read your variables and mixins, you need to import them directly in the files that use them and not on your global styles file.
On _globals.scss and _header.scss add:
#use "variables" as *;
#use "mixins" as *;
Additionally, if you don't want to import both files every time, you can create a new file that will forward them and then import only this file:
// _settings.scss (or any other name)
#forward "variables";
#forward "mixins";
// _globals.scss & _header.scss
#use "settings" as *;

NativeScript 8 not compiling SCSS to CSS

In my project, I have two scss empty login component files.
If the component loads the CSS:
styleUrls: ["./login-common.css", "./login.css"]
when I run ns run ios the compiler would throw a CSS not found error.
If I change it to SCSS
styleUrls: ["./login-common.scss", "./login.scss"]
I don't have any errors but the login screen on the simulator is blank
If I comment the styleUrls line, the login screen would be rendered.
I think I should use the .css version, and probably add/remove some dependency and probably change some config files. Any idea?
My package.json :
"devDependencies": {
"#angular/compiler-cli": "~11.2.7",
"#nativescript/ios": "8.0.0",
"#nativescript/types": "~8.0.0",
"#nativescript/webpack": "beta",
"#ngtools/webpack": "~11.2.6",
"sass-loader": "^12.1.0",
"typescript": "~4.0.0",
"webpack": "^5.49.0"
},
My webpack.config.js:
const webpack = require("#nativescript/webpack");
module.exports = (env) => {
webpack.init(env);
webpack.chainWebpack(config => {
config.module
.rule('scss')
.use('sass-loader')
.options({ sassOptions: { indentedSyntax: false } })
})
return webpack.resolveConfig();
};
You need to run
npm i sass
That will install the sass interpreter.
And add a test to your webpack config
config.module
.rule('scss')
.test( /\.s[ac]ss$/i)
.use(
// Compiles Sass to CSS
"sass-loader"
)

Include node_modules css in Vuejs application that uses scss

I have deployed my application to aws and I see that the application renders fine, except that the syncfusion controls do not render correctly. Google chrome console does not show any errors.
The application renders correctly in my local machine.
To fix this, it was suggested I move the import '#syncfusion/**/styles/material.css' statements in the individual vue component to App.vue (as documented here). I however get a "Failed to resolve loader: sass-loader, You may need to install it" error(the application has node-sass, sass-loader installed already).
How should I include css files along with scss files, in my application?
Before: vocabulary.vue:
<script>
import '#syncfusion/ej2-base/styles/material.css';
import '#syncfusion/ej2-vue-inputs/styles/material.css';
package.json:
"devDependencies": {
"node-sass": "^4.12.0",
"sass-loader": "^7.1.0",
}
vue.config.js:
module.exports = {
publicPath: '/',
transpileDependencies: [
'vue-echarts',
'resize-detector'
],
configureWebpack: {
devtool: 'source-map',
optimization: {
splitChunks: {
chunks: 'all'
}
}
}
}
App.Vue:
<style>
#import "../node_modules/#syncfusion/ej2-base/styles/material.css";
#import "../node_modules/#syncfusion/ej2-vue-inputs/styles/material.css";
</style>
Deleting the npm packages and re-installing them again fixed the issue.

Add SCSS support to Vue project

In my packages.json file by default I get:
"postcss": {
"plugins": {
"autoprefixer": {}
}}
When I add <style lang='scss'> It doesn't compile like magic like it does for Typescript support. I know I will need to specify some NPM package as devDependencies and specify something above in the postcss section to get scss to compile, but I can't find any documentation outside of webpack so I am lost.
See https://vue-loader.vuejs.org/guide/pre-processors.html.
For example, to compile our <style> tag with SASS/SCSS:
npm install -D sass-loader node-sass
In your webpack config:
module.exports = {
module: {
rules: [
// ... other rules omitted
// this will apply to both plain `.scss` files
// AND `<style lang="scss">` blocks in `.vue` files
{
test: /\.scss$/,
use: [
'vue-style-loader',
'css-loader',
'sass-loader'
]
}
]
},
// plugin omitted
}
Now in addition to being able to import 'style.scss', we can use SCSS
in Vue components as well:
<style lang="scss"> /* write SCSS here */ </style>
Any content inside the block will be processed by webpack as if it's
inside a *.scss file.

How to add global style to angular 6/7 library

I was trying to add global styles in the same way like in angular app, but it totally does not work.
My libraries' name is example-lib, so I added styles.css to /projects/example-lib/. I added styles in main angular.json file:
...
"example-lib": {
"root": "projects/example-lib",
"sourceRoot": "projects/example-lib/src",
"projectType": "library",
"prefix": "ngx",
"architect": {
"build": {
"builder": "#angular-devkit/build-ng-packagr:build",
"options": {
"tsConfig": "projects/example-lib/tsconfig.lib.json",
"project": "projects/example-lib/ng-package.json",
"styles": [
"projects/example-lib/styles.css" <!-- HERE
],
},
...
But when I tried build library using command:
ng build example-lib
I got error:
Schema validation failed with the following errors:
Data path "" should NOT have additional properties(styles)
I guess that is the other way to add global styles in separate library. Anyone can help me?
I have a workaround for this. Just create the root component of your library without view encapsulation and all its styles will be then global.
my-library.component.ts
import { Component, OnInit, ViewEncapsulation } from '#angular/core';
#Component({
selector: 'lib-my-library',
templateUrl: './my-library.component.html',
styleUrls: ['./my-library.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class MyLibraryComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
my-library.component.html
<!-- html content -->
my-library.component.scss
#import './styles/core.scss';
Now your my-library.component.scss and core.scss are global
styles/core.scss
body {
background: #333;
}
core.scss is optional, I just like to keep the root files clean.
Update: In case you want your mixins and variables too, then follow this answer.
As #codeepic already pointed out, there is currently a standard solution.
In ng-package.json add
"assets": ["./styles/**/*.css"]
The provided paths should be the paths to your files. At the same time, they will be the paths inside your /dist folder.
On build, the files will be copied to /dist. Users of your library will be able to add them to their global styles as follows.
/* styles.css */
#import url('node_modules/<your-library-name>/styles/<file-name>');
This way you can copy any type of files.
P.S. When used with CSS, do not forget that you can create an index.css file that can be imported just like node_modules/<your-library-name>/styles.
From Compiling css in new Angular 6 libraries:
install some devDependencies in our library in order to bundle the css:
ng-packagr
scss-bundle
ts-node
Create css-bundle.ts:
import { relative } from 'path';
import { Bundler } from 'scss-bundle';
import { writeFile } from 'fs-extra';
/** Bundles all SCSS files into a single file */
async function bundleScss() {
const { found, bundledContent, imports } = await new Bundler()
.Bundle('./src/_theme.scss', ['./src/**/*.scss']);
if (imports) {
const cwd = process.cwd();
const filesNotFound = imports
.filter(x => !x.found)
.map(x => relative(cwd, x.filePath));
if (filesNotFound.length) {
console.error(`SCSS imports failed \n\n${filesNotFound.join('\n - ')}\n`);
throw new Error('One or more SCSS imports failed');
}
}
if (found) {
await writeFile('./dist/_theme.scss', bundledContent);
}
}
bundleScss();
Add _theme.scss inside the /src directory of the library that actually contains and imports all the css that we want to bundle.
Add postbuild npm script to run the css-bundle.ts
Include it in the styles tag in your Application in the angular.json
From this issue solution
Install cpx and scss-bundle as Dev dependencies to your package.json. Then add the following entries in your package.json "scripts" property:
"scripts": {
...
"build-mylib": "ng build mylib && npm run build-mylib-styles && npm run cp-mylib-assets",
"build-mylib-styles": "cpx \"./projects/mylib/src/lib/style/**/*\" \"./dist/mylib/style\" && scss-bundle -e ./projects/mylib/src/lib/style/_style.scss -d ./dist/mylib/style/_styles.scss",
"cp-mylib-assets": "cpx \"./src/assets/**/*\" \"./dist/mylib/assets\"",
...
}
Replace "mylib" with your real library name and then just run in your terminal build-mylib. That would compile your scss assets to your dist folder.
You use this global styles in your actual Angular project just import them in your angular.json file within your project settings:
"styles": [
"src/styles.scss",
"dist/my-shiny-library/_theme.scss"
],
(use dist if your project is in the same workspace, or node_moduled if its an imported library)
1- be sure you are putting your styles inside the library
example:
projects/your-lib-name/assets/styles.css
2- then in your ng-package.json (in the lib for sure) put the assets rule
{
"$schema": ... ,
"dest": ... ,
> "assets": [
> "./assets/*"
> ],
"lib": ...
}
3-
in your application, you can use this asset
"styles": [
"../your-lib-name/assets/styles.css"
]
this is a tutorial

Resources