problem in accessing the scss variables in react components - reactjs

Followed the link https://mattferderer.com/use-sass-variables-in-typescript-and-javascript
Looking to access the scss varaibles in react component . Not sure with what import name i need to call in react component since if i give as below import statement it is showing an error as cannot find the module '../scss/_variables.scss';
import _variables from '../scss/_variables.scss';
here _variables.scss is the file name which contains
// variables.scss
$white-color: #fcf5ed;
:export {
whitecolor: $white-color; }
I am scratching my head to get the "whitecolor" variable available in react component .
Also, I am using webpack as below
{
test: '/.scss$/',
use: [{
loader: 'style-loader' // creates style nodes from JS strings
}, {
loader: 'css-loader' // translates CSS into CommonJS
}, {
loader: 'sass-loader' // compiles Sass to CSS
}]
}
Any help would be highly appreciated!!

Importing specific property in React does not work unless it is a module.
I was facing the same problem and here is what I did:
Renamed _variables.scss to _variables.module.scss and then the import is import _variables from '../scss/_variables.module.scss';
now you can access the scss variables just like _variables.whitecolor

On the react app, you can import the variable.scss in App.scss file. If there is no file just create it.
make sure that you have installed node-sass.
#import "../scss/_variables.scss";
Now the variables are accessible, I am using React Webpack.
Also, we have other options please check here
Thanks,
Prem

One way would be to npm install node-sass
Then change your app.css to app.scss and in there you import your stylesheet:
#import '../scss/_variables.scss';
Then you can use it like
.App-link {
color: $secondary-color;
}

Related

SCSS doesn't load on Gatsby

i try to load the SASS for my Gatsby Project but if I check the source code of the web there isn't any classes from my sass.
I am a bit confused and I followed the documentation of Gatsby.
Nothing worked so my last chance is SO.
// gatsby-config.js
plugins: [
'gatsby-plugin-react-helmet',
'gatsby-plugin-fontawesome-css',
'gatsby-plugin-sass',
{
resolve: 'gatsby-source-filesystem',
options: {
name: 'assets',
path: `${__dirname}/static/`,
},
},
]
Here I import the style.
/**
* Add browser relation logic.
*/
require('./style/global.js');
import './style/sass/index.scss';
I followed the gatsby-plugin-sass documentation and I should be all set. After restarting the server and show source-code of my app there is now class name from my sass file.
Best Regards
Knome
I didn't integrate in any component. Because if I see the Source code
of chrome then there should be scss be loaded.
Ok, well... The SCSS is loaded as it should but the styles are not applied to any component because you've not set any class name.
Just do:
const IndexPage =()=>{
return <div className="grid-container">I'm your index page</div>
}
Like any other HTML element.

Tree shaking not working for the react component library using named imports

Our company projects count is growing, so we decided to move our ui kit to a separate private npm package. For building kit before publishing we decided to use rollup.
The file structure for ui kit is quite standard we've:
src
- Components
- Alert
- Button
- Heading
- ...
HOC, static...
- index.js
Root index.js file is used only for reexporting all components.
export {default as Alert} from './Components/Alert';
export {default as Button} from './Components/Button';
...
Our main goal is to be able to get components from our kit using named imports.
import {Alert, Button} from '#company/ui-kit';
Properly working tree shaking is also important, because some of our projects are using only 2/31 components from the kit, so we want to see in final build only components what has been used and this is the main challenge. We tried many options of rollup config with single output file or chunks and realized, that tree shaking only works with chunks and what's more interesting it works only with importing chunk directly, not named import from the index.js.
import Alert from '#company/ui-kit/Alert'; // tree shaking works, only Alert get into build
import {Alert} from '#company/ui-kit'; // tree shaking not working, all kit components are got into the build
Could somebody explain me why this is happening? And is there any way to use named imports with properly working tree shaking. What is also very curious, that we tried to test tree shaking with named imports in some popular libraries like material ui and there it's not working too. Tree shaking works only with direct import from chunk.
Also need to mention that we tested tree shaking only in projects created with create-react-app. I don't really think the problem could be inside create-react-app bundler config, but maybe it will help to figure out this.
For the full picture also attaching our rollup config:
import multiInput from 'rollup-plugin-multi-input';
import babel from 'rollup-plugin-babel';
import commonjs from 'rollup-plugin-commonjs';
import external from 'rollup-plugin-peer-deps-external';
import resolve from 'rollup-plugin-node-resolve';
import copy from 'rollup-plugin-copy'
import postcss from 'rollup-plugin-postcss';
import postcssUrl from 'postcss-url';
import asset from "rollup-plugin-smart-asset";
export default {
input: ['src/index.js', 'src/Components/**/*.js'],
output: [
{
dir: './',
format: 'cjs',
sourcemap: true,
exports: 'auto',
chunkFileNames: '__chunks/[name]_[hash].js'
}
],
plugins: [
multiInput({relative: 'src/'}),
external(),
postcss({
modules: false,
extract: true,
minimize: true,
sourceMap: true,
plugins: [postcssUrl({url: 'inline', maxSize: 1000})],
}),
copy({targets: [{src: 'src/static/icons/fonts/*', dest: 'fonts'}]}),
babel({exclude: 'node_modules/**'}),
asset({url: 'copy', keepImport: true, useHash: false, keepName: true, assetsPath: 'assets/'}),
resolve(),
commonjs({include: 'node_modules/**'})
]
};
Thanks in advance for your replies!

Webpack + `create-react-app` | ProvidePlugin Not Loading React as a Module

* Note: I barely know anything about Webpack.
I want to load the react node module and other modules in Webpack via ProvidePlugin to have global access to them.
I created a create-react-app and ran eject and got access the pre-defined configuration for Webpack create-react-app provides.
I read this post about loading react globally via PluginProvidor and read about PluginProvidor itself in the Webpack docs, where the latter states:
By default, module resolution path is current folder (./**) and node_modules
Based on that, in webpack.config.js, in plugins, I added the following PluginProvidor:
...
plugins: [
new webpack.ProvidePlugin(
{
React: 'react'
}
)
]
...
But it didn't work - in a JSX file when I call React (e.g class MyComponent extends React.Component { ... }) I get an error that says that React isn't defined (and also a React-specfic error that React must be defined in JSX files).
Why doesn't it work? As far as I understand, I'm giving the same identifier I call in my JSX file, and like I mentioned, according to the Webpack docs, to the path of the react module in node_modules - both as required for it to work.
My configuation file: webpack.config.js
It's not a good idea to use ProvidePlugin, and even worse is to eject your CRA.
Instead of ProvidePlugin use globals:
// globals.js
import React from 'react';
window.React = React;
and then import './globals'
import './globals';
// no need import React
import ReactDOM from 'react-dom';
...
For adding plugins to CRA web pack refer to react-app-rewired.
Example of adding a plugin:
/* config-overrides.js */
const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin');
module.exports = function override(config, env) {
if (!config.plugins) {
config.plugins = [];
}
config.plugins.push(new MonacoWebpackPlugin());
return config;
};
Demo:

SASS Font Import nesting issue

Within my react app I have a folder structure like so:
src
-assets
-fonts
-components
-NormalComponents
-ContentCards
-CardType1
-CardType2
-containers
-styles
etc
I'm importing a mixin.scss file which is located within the styles folder. This contains a mixin function to import fonts from the following path: src/assets/fonts/myfonthere.ttf
Here is my function:
#mixin font-face($font-family, $file-path) {
#font-face {
font-family: $font-family;
src: url('#{$file-path}.eot');
src: url('#{$file-path}.woff');
src: url('#{$file-path}.ttf');
}
}
#include font-face(MyFont-Bold, '../assets/fonts/MyFont-Bold');
I can import this mixin with no errors at the src/components/NormalComponents level however, when I to import at src/components/ContentCards/CardType1 errors are thrown.
Error: Module not found: Can't resolve '../../assets/fonts/MyFont-Bold.eot'
Is this due to the nested folder structure for the Content Cards component? Is there any way around this so I can import the mixin at any level and not have this issue?
I don't think it's a problem about nested folder structure.Is it possible that you import mixin file from styles directory, after add a more doctor ,your {file-path} has something wrong?

create-react-app 2.0, how to use absolute path import in sass/scss files?

I am using creacte-react-app 2.0.0-next.66cc7a90, which already has support for Sass/Scss files
however with default relative import in Sass/Scss files, i have to use code like
#import "../../../../../styles/variables/_variables.scss";
instead I want to use absolute import so i can import with code
#import "styles/variables/_variables.scss";
I know one way to acheve so is to update options
{
loader: "sass-loader",
options: {
includePaths: ["absolute/path/a", "absolute/path/b"]
}
but I want to do it without ejecting, how can i do it? using react-app-rewired?
Add the required root include paths to SASS_PATH environment variable.
It can be set either when you run the yarn or npm commands or in a .env file.
Example
// my-component.jsx
import React from 'react';
import './my-component.scss';
class MyComponent extends React.Component {
render() {
return (<div className="container">Hello</div>);
}
}
// my-component.scss
#import 'styles/abstracts/variables';
.container {}
Assuming styles/abstracts/_variables.scss exists under src, you could do the following:
SASS_PATH=src yarn start
OR
echo SASS_PATH=src > .env
yarn start

Resources