React font error - reactjs

I have the following in my SASS component:
#font-face {
font-family: 'icomoon';
src: url('../fonts/icomoon.eot');
src: url('../fonts/icomoon.eot') format('embedded-opentype'),
url('../fonts/icomoon.ttf') format('truetype'),
url('../fonts/icomoon.woff') format('woff'),
url('../fonts/icomoon.svg') format('svg');
font-weight: normal;
font-style: normal;
}
#font-face {
font-family: 'Graphink Regular';
src: url('../fonts/GraphikRegular.ttf') format('truetype');
font-weight: normal;
font-style: normal;
}
the first rule for icomoon works fine however webpack is complaining about the second throwing the following error:
ERROR in ./public/fonts/GraphikRegular.ttf
Module build failed: Error: Cannot find module 'file-loader'
at Function.Module._resolveFilename (module.js:469:15)
at Function.Module._load (module.js:417:25)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.module.exports (/Users/alessandro.santese/Desktop/Alessandro/AIA/projects/accenture-tshirtbuilder/tshirtbuilder/node_modules/url-loader/index.js:18:20)
# ./~/css-loader!./~/sass-loader!./public/sass/typography.scss 6:514-552
this is my webpack.config
var webpack = require('webpack');
var path = require('path');
var BUILD_DIR = path.resolve(__dirname, 'public/js/');
var APP_DIR = path.resolve(__dirname, 'jsx');
var config = {
entry: APP_DIR + '/index.jsx',
output: {
path: BUILD_DIR,
filename: 'app.js'
},
module : {
loaders : [
{
test : /\.jsx?/,
include : APP_DIR,
loader : 'babel'
},
{
test: /\.scss$/,
loaders: ['style', 'css', 'sass']
},
{
test: /\.(eot|woff|woff2|ttf|svg|png|jpg)$/,
loader: 'url-loader?limit=30000&name=[name]-[hash].[ext]'
}
]
}
};
module.exports = config;
all the fonts are excately in the same folder called "fonts".

The error claims it doesn't found the file-loader module. That module is a peerDependency for the url-loader module, maybe you don't have it yet installed. Try to install the module:
npm install --save-dev file-loader

Related

How to add custom font using #fontface to Storybook? (Need updated answer for storybook version 6.5.5)?

I have tried all the solutions available online to add custom font in the Storybook but failed.
Following are the files under .storybook folder that I have added as per this solution:
webpack.config.js :
const path = require('path');
module.exports = async ({ config }) => {
// fonts
config.module.rules.push({
test: /\.(png|woff|woff2|eot|ttf|svg)$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
},
},
],
include: path.resolve(__dirname, '../'),
});
return config;
};
preview.head.html
<style type="text/css">
#font-face {
font-family: 'Eina';
src: url('../src/styles/Eina03-Regular.ttf') format('truetype');
font-weight: 400;
font-style: normal;
}
#font-face {
font-family: 'Eina';
src: url('../src/styles/Eina03-SemiBold.ttf') format('truetype');
font-weight: 600;
font-style: normal;
}
#font-face {
font-family: 'Eina';
src: url('../src/styles/Eina03-Bold.ttf') format('truetype');
font-weight: 700;
font-style: normal;
}
</style>
main.js
const path = require('path');
module.exports = {
stories: ['../src/**/*.stories.mdx', '../src/**/*.stories.#(js|jsx|ts|tsx)'],
staticDirs: ['../public', '../public/fonts'],
addons: [
'#storybook/addon-links',
'#storybook/addon-essentials',
'#storybook/addon-interactions',
{
name: '#storybook/addon-postcss',
options: {
postcssLoaderOptions: {
implementation: require('postcss'),
},
},
},
],
framework: '#storybook/react',
core: {
builder: 'webpack5',
},
webpackFinal: async config => {
config.module.rules.push({
test: /\.scss$/,
use: ['style-loader', 'css-loader', 'sass-loader'],
include: path.resolve(__dirname, '../'),
});
return config;
},
};
The font is stored in src/styles/.
Also, I already have main.js file so I ignored the config.js, which needed to be added as per the solution
Any help will be highly appreciated.
I had issues using the file-loader based approach as well. Here's how I got it working:
Folder structure
├── .storybook/
│ ├── main.js
│ └── preview-head.html
└── src/
└── assets/
└── fonts/
└── custom-font.otf
preview-head.html
<style type="text/css">
#font-face {
font-family: 'custom-font';
src: url('fonts/custom-font.otf');
}
</style>
main.js
const path = require('path');
module.exports = {
stories: [...],
addons: [...],
staticDirs: ['../src/assets'],
framework: '#storybook/react',
};
The key here is staticDirs. You'll be able to reference all your assets relatively from what you've defined there.
To answer your case more directly, you need to update your staticDirs to include src/styles and reference your fonts in the #font-face src by url('Eina03-Regular.ttf')

Error during bundle: Error: Unexpected character '' (Note that you need plugins to import files that are not JavaScript)

I added font to react typescript project after that I try to build but its showing error
Error during bundle: Error: Unexpected character '' (Note that you need plugins to import files that are not JavaScript)
Adding font using styled-components and loader using is url-loader
fonts work fine in system and no error while run.
Font extension is ttf. Below is my style file using styled-component
import IBMPlexSansSemiBold from './fonts/IBMPlexSans/IBMPlexSans-SemiBold.ttf';
import IBMPlexSansBold from './fonts/IBMPlexSans/IBMPlexSans-Bold.ttf';
import { font} from './Fonts';
export const FontsIBM = createGlobalStyle`
#font-face {
font-family: ${font.DEFAULT.SEMI_BOLD};
src: local('IBMPlexSans-SemiBold'), local(${font.DEFAULT.SEMI_BOLD}),
url(${IBMPlexSansSemiBold}) format('truetype');
font-weight: 600;
font-style: normal;
}
#font-face {
font-family: ${font.DEFAULT.BOLD};
src: local('IBMPlexSans-Bold'), local(${font.DEFAULT.BOLD}),
url(${IBMPlexSansBold}) format('truetype');
font-weight: 700;
font-style: normal;
}
`;
This is how I config url-loader
const rootMain = require('../../../.storybook/main');
module.exports = {
...rootMain,
core: { ...rootMain.core, builder: 'webpack5' },
stories: [
...rootMain.stories,
'../src/lib/**/*.stories.mdx',
'../src/lib/**/*.stories.#(js|jsx|ts|tsx)',
],
addons: [...rootMain.addons, '#nrwl/react/plugins/storybook'],
staticDirs: ['../../../public'],
webpackFinal: async (config, { configType }) => {
// apply any global webpack configs that might have been specified in .storybook/main.js
if (rootMain.webpackFinal) {
config = await rootMain.webpackFinal(config, { configType });
}
//Font added using url-loader
config.module.rules.push({
test: /\.(ttf|eot|woff|woff2)$/,
loader: require.resolve('url-loader'),
options: {
name: '[name].[hash].[ext]',
},
});
// add your own webpack tweaks if needed
return config;
},
};

SCSS file cannot import node_module

Tried #import "~react-icons" in an SCSS file.
I get an error: Module build failed:
#import "~react-icons";
^
File to import not found or unreadable: ~react-icons.
This was an npm module that I installed and is on package-json.
My scss code looks like this, the error is at the first line:
#import "~react-icons";
input {
width: 100%;
box-sizing: border-box;
border: 2px solid #ccc;
border-radius: 4px;
font-size: 16px;
background-color: white;
padding: 12px 20px 12px 20px;
margin-bottom: 20px;
}
My webpack configuration looks like this:
const webpack = require('webpack');
const path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
let BUILD_DIR = path.resolve(__dirname, 'dist');
let APP_DIR = path.resolve(__dirname, 'src');
let config = {
entry: path.join(APP_DIR, '/index.js'),
output: {
path: BUILD_DIR,
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.jsx?/,
include: APP_DIR,
loaders: ['babel-loader']
},
{
test: /\.scss$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: ['css-loader', 'sass-loader'],
publicPath: "/dist"
})
},
{
test: /\.(ttf|eot|svg|gif|woff(2)?)(\?[a-z0-9]+)?(\?v=
[0-9]\.[0-9]\.[0-9])?$/,
loader: 'file-loader',
}
]
},
resolve: {
extensions: ['.js', '.jsx']
},
devServer: {
contentBase: path.join(__dirname),
// serve index.html in place of 404 responses to allow HTML5
// history
historyApiFallback: true
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new HtmlWebpackPlugin({
title: 'Project',
minify: {
collapseWhitespace: true
},
hash: true,
template: './index.html'
}),
new ExtractTextPlugin({
filename: 'style.css',
disable: false,
allChunks: true
})
]
};
module.exports = config;
There is not an scss file to import for react-icons. You have to import the icons in the file you want to use:
import FaSearch from 'react-icons/lib/fa/search';
class Search extends React.Component {
render() {
return <FaSearch />
}
}

React webpack application not loading Roboto Font

I am working on React application where i want to use Roboto Font.I have followed the process to load the roboto Font. Following is my Project Structure :
My Index.css file
#font-face {
font-family: 'Roboto-Light';
src: url('./Roboto-Light.eot');
src: url('./Roboto-Light.eot?#iefix') format('embedded-opentype'),
url('./Roboto-Light.woff') format('woff'),
url('./Roboto-Light.ttf') format('truetype'),
url('./Roboto-Light.svg#RobotoLight') format('svg');
font-weight: 100;
font-style: normal;
}
My webpack.config.js :
const webpack = require('webpack');
const { resolve } = require('path');
module.exports = {
devtool: 'cheap-module-eval-source-map',
entry: [
resolve(__dirname, 'src', 'js/index'),
],
output: {
filename: '[name].[hash].js',
path: resolve(__dirname, 'build')
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
}
},
{
test: /\.s?css$/,
use: [
'style-loader',
'css-loader?sourceMap&camelCase&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]',
'sass-loader?sourceMap'
]
},
{
test: /\.(jpg|jpeg|gif|png)$/,
exclude: /node_modules/,
use: [
'url-loader?limit=1024&name=images/[name].[ext]'
]
},
{
test: /\.(woff|woff2|eot|ttf|svg)$/,
use: ['file-loader?name=src/fonts/[name].[ext]']
},
{
test: /\.(json)$/,
use: ['file-loader?name=[name].[ext]']
}
]
}
}
and using css to load font as :
body {
font-family: 'Roboto-Light' !important;
}
I have followed this tutorial but its not working as expected and font is not loaded on webpage. Thanks in advance.
I didnt got any solution as of now.
Added Screenshot as per requested
Look like the app couldn't load the font face.
Please try:
in src/js/index.js: remove the line
import '../fonts/index.css';
rename file index.css to roboto.scss
in src/fonts/roboto.scss use absolute path instead of relative path:
#font-face {
font-family: 'Roboto-Light';
src: url('/src/fonts/Roboto-Light.eot');
src: url('/src/fonts/Roboto-Light.eot?#iefix') format('embedded-opentype'),
url('/src/fonts/Roboto-Light.woff') format('woff'),
url('/src/fonts/Roboto-Light.ttf') format('truetype'),
url('/src/fonts/Roboto-Light.svg#RobotoLight') format('svg');
font-weight: 100;
font-style: normal;
}
in src/css/styles.scss add:
#import "../fonts/roboto";
You can also take a look at this commit.
Update 1
You can use WhatFont chrome extension to check. it's Roboto Light.
Update 2
I found that you must use absolute http url because app can't find your font with normal path.
src/fonts/roboto.scss
#font-face {
font-family: 'Roboto-Light';
src: url('http://localhost:8089/fonts/Roboto-Light.eot');
src: url('http://localhost:8089/fonts/Roboto-Light.eot?#iefix') format('embedded-opentype'),
url('http://localhost:8089/fonts/Roboto-Light.woff') format('woff'),
url('http://localhost:8089/fonts/Roboto-Light.ttf') format('truetype'),
url('http://localhost:8089/fonts/Roboto-Light.svg#RobotoLight') format('svg');
font-weight: 100;
font-style: normal;
}
And the result:

Webpack error when compiling sass

I have a sass component like so:
#font-face {
font-family: 'icomoon';
src: url('../fonts/icomoon.eot');
src: url('../fonts/icomoon.eot') format('embedded-opentype'),
url('../fonts/icomoon.ttf') format('truetype'),
url('../fonts/icomoon.woff') format('woff'),
url('../fonts/icomoon.svg') format('svg');
font-weight: normal;
font-style: normal;
}
[class^="icon-"], [class*=" icon-"] {
/* use !important to prevent issues with browser extensions that change fonts */
font-family: 'icomoon' !important;
speak: none;
font-style: normal;
font-weight: normal;
font-variant: normal;
text-transform: none;
line-height: 1;
/* Better Font Rendering =========== */
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.icon-close2:before {
content: "\e66d";
}
.icon-checkmark2:before {
content: "\ea11";
}
and a webpack config like this:
var webpack = require('webpack');
var path = require('path');
var BUILD_DIR = path.resolve(__dirname, 'public/js/');
var APP_DIR = path.resolve(__dirname, 'jsx');
var config = {
entry: APP_DIR + '/index.jsx',
output: {
path: BUILD_DIR,
filename: 'app.js'
},
module : {
loaders : [
{
test : /\.jsx?/,
include : APP_DIR,
loader : 'babel'
},
{
test: /\.scss$/,
loaders: ['style', 'css', 'sass']
}
]
}
};
module.exports = config;
as soon as I had the sass component above I get the following error:
ERROR in ./public/fonts/icomoon.ttf Module parse failed:
/Users/alessandro.santese/Desktop/Alessandro/AIA/projects/accenture-tshirtbuilder/tshirtbuilder/public/fonts/icomoon.ttf
Unexpected character '' (1:0) You may need an appropriate loader to
handle this file type.
and many others like this for the other fonts
Your webpack configuration misses a loader for ttf file. I think you should use the url loader in your case.
Add to your loader
{
test: /\.(eot|woff|woff2|ttf|svg|png|jpg)$/,
loader: 'url-loader?limit=30000&name=[name]-[hash].[ext]'
}
You'll need to install it: npm install url-loader --save-dev

Resources