SASS Font Import nesting issue - reactjs

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?

Related

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!

How to import a sound file into react typescript component?

I have a small mp3 file located in project_root/src/audio/alarm.mp3.
I try to import like so:
import alarm from "./audio/alarm.mp3";
But when I try to import it into App.tsx, I get this compiler error:
Cannot find module './audio/alarm.mp3'.
But I can import images just fine.
Place the audio in the assets and write a custom typing file called audio.d.ts with the following code :-
declare module '*.mp3';
and place it in the root of your project under any name, ex: ./custom_typings/audio.d.ts.
Here, I have just done it for an mp3 file.
After this go to your tsconfig.json and under "typeRoots" add the custom_typings folder.
"typeRoots": [
"node_modules/#types",
"custom_typings/"
]
Once this is done you can just import the audio file from anywhere and use it normally as you would.
import {audioFile} from '../../../../assets/audio/audioFile.mp3';
TrackPlayer.add({
id: '1',
url: audioFile,
title: 'Example title',
artist: 'Example Artist',
artwork: 'https://picsum.photos/100',
});
Found a solution to the issue. Instead of using ES6 import use ES5 require() for audio files. It works and the typescript compiler doesn't complain.
const alarm = require("./audio/alarm.mp3");
You can add typing to the mp3 files, if you are using typescript. To do this, create a types directory at the root directory with a defined file asset.d.ts and include in your configuration file:
types/asset.d.ts
declare module "*.mp3" {
const value: any;
export default value;
}
Then, add this to tsconfig.json:
tsconfig.json
{
"compilerOptions": {
//...
},
"include": [
"src/*",
"types/*"
]
}
Place it in the assets folder in order to access it.
The following is on how to use it with images, however it works the same with audio files:
How to load image (and other assets) in Angular an project?

problem in accessing the scss variables in react components

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;
}

Creating a local ReactJS library and importing it in another project (using npm)

I have created one local library project 'uilibrary' using create-react-app and importing this in another react project ('actualproject').
Both the project folders are in 'root' folder as follows:
root
/uilibrary
/actualproject
The uilibrary project has following structure:
/uilibrary
/src
/lib
/TopBar
index.js
index.js
I am exporting ToolBar from /uilibrary/index.js as follows:
import TopBar from "./lib/TopBar";
export { TopBar };
In the 'actualproject' react project I have following in "package.json":
{
...
"dependencies": {
"uilibrary": "file:../uilibrary"
}
...
}
In the 'actualproject' importing ToolBar from uilibrary does not work:
import TopBar from 'uilibrary';
Above code gives following error:
Cannot find module: 'uilibrary'. Make sure this package is installed.

Typescript + Reactjs - Imported svg does not render

I was migrating some of my React files over to .tsx files and had errors on my svg imports:
import logo from './logo.svg'; // [ts] cannot find module './logo.svg'
So, I changed it to:
const logo = require('./logo.svg') as string
which fixed up the transpiler errors.
I am rendering it using React Bootstrap's Image tag:
<Image src={logo} className="..." />
However, that image does not render at all. I have tried changing the type to as any but no cigar. Can anyone help me?
Make sure you have the file images.d.ts in your root folder (next to tsconfig.json, etc) with the following contents:
declare module '*.svg'
declare module '*.png'
declare module '*.jpg'

Resources