Webpack error when compiling sass - reactjs

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

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

Correct use of MiniCssExtractPlugin in a SSR React-TypeScript app

I have a SSR React-TypeScript app, built on Webpack 4 and I use SCSS for each React component. I use two Webpack config files, one for the client bundle and one for the server bundle.
I am in a bind as to how to use the MiniCssExtractPlugin to load my SCSS on the client Webpack config. The documentation isn't very helpful. It is evident that this rule is necessary inside modules:
{
test: /\.scss$/,
use: [
MiniCssExtractPlugin.loader,
"css-loader",
"sass-loader"
]
}
But it isn't clear what file should go here:
plugins: [
new webpack.HotModuleReplacementPlugin(),
new MiniCssExtractPlugin({
filename: devMode ? '[name].css' : '[name].[hash].css',
chunkFilename: devMode ? '[id].css' : '[id].[hash].css',
})
],
My SCSS files are spread throughout my application: each React component has its own SCSS file. I don't know how to pass these files to MiniCssExtractPlugin.
For the server Webpack config, I have the following to load my SCSS files and I don't know whether or not it's sufficient:
{
test: /\.scss$/,
use: ["css-loader", "sass-loader"]
}
I would love to see an actual working example of a similar app, if possible.
My css file as generated by MiniCSS:
.home {
text-align: center; }
.home-logo {
animation: home-logo-spin infinite 20s linear;
height: 40vmin;
pointer-events: none; }
.home-header {
background-color: #282c34;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white; }
.home-link {
color: #61dafb; }
#keyframes home-logo-spin {
from {
transform: rotate(0deg); }
to {
transform: rotate(360deg); } }
/*# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9zcmMvY2xpZW50L3ByZXNlbnRhdGlvbmFsLWNvbXBvbmVudHMvaG9tZS9Ib21lLnNjc3MiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUE7QUFDQSxxQkFBcUI7O0FBRXJCO0FBQ0E7QUFDQTtBQUNBLHVCQUF1Qjs7QUFFdkI7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLGVBQWU7O0FBRWY7QUFDQSxpQkFBaUI7O0FBRWpCO0FBQ0E7QUFDQSw0QkFBNEI7QUFDNUI7QUFDQSw4QkFBOEIsRUFBRSIsImZpbGUiOiJzdHlsZXMuY3NzIiwic291cmNlc0NvbnRlbnQiOlsiLmhvbWUge1xuICB0ZXh0LWFsaWduOiBjZW50ZXI7IH1cblxuLmhvbWUtbG9nbyB7XG4gIGFuaW1hdGlvbjogaG9tZS1sb2dvLXNwaW4gaW5maW5pdGUgMjBzIGxpbmVhcjtcbiAgaGVpZ2h0OiA0MHZtaW47XG4gIHBvaW50ZXItZXZlbnRzOiBub25lOyB9XG5cbi5ob21lLWhlYWRlciB7XG4gIGJhY2tncm91bmQtY29sb3I6ICMyODJjMzQ7XG4gIG1pbi1oZWlnaHQ6IDEwMHZoO1xuICBkaXNwbGF5OiBmbGV4O1xuICBmbGV4LWRpcmVjdGlvbjogY29sdW1uO1xuICBhbGlnbi1pdGVtczogY2VudGVyO1xuICBqdXN0aWZ5LWNvbnRlbnQ6IGNlbnRlcjtcbiAgZm9udC1zaXplOiBjYWxjKDEwcHggKyAydm1pbik7XG4gIGNvbG9yOiB3aGl0ZTsgfVxuXG4uaG9tZS1saW5rIHtcbiAgY29sb3I6ICM2MWRhZmI7IH1cblxuQGtleWZyYW1lcyBob21lLWxvZ28tc3BpbiB7XG4gIGZyb20ge1xuICAgIHRyYW5zZm9ybTogcm90YXRlKDBkZWcpOyB9XG4gIHRvIHtcbiAgICB0cmFuc2Zvcm06IHJvdGF0ZSgzNjBkZWcpOyB9IH1cbiJdLCJzb3VyY2VSb290IjoiIn0=*/

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:

React font error

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

Resources