React components have css files which i did not imported - css

i just imported one scss file in my component landing page
import React, { Component } from 'react';
import FeaturedRestaurant from '../restaurant/RestaurantFeatured';
import './css/landing_style.scss';
but when i see to console it has six css files which i imported in other components, I have doubt like webpack make available scss file to all other components
screen shot is below
this is my webpack config
var path = require('path');
var webpack = require('webpack');
require('babel-core/register');
require('babel-polyfill');
module.exports = {
entry: ['babel-polyfill', './src/index.js'],
output: {
path: '__dirname',
filename: 'bundle.js'
},
resolve: {
extensions: ['', '.js', '.jsx']
},
module: {
loaders: [
{
test: /\.jsx?$/,
loader: 'babel',
exclude: /node_modules/,
query: {
cacheDirectory: true,
presets: ['react', 'es2015', 'stage-1']
}
},
{
test: /\.sass$/,
loaders: ['style', 'css', 'sass']
},
{
test: /\.scss$/,
loaders: ['style', 'css', 'sass']
},
{
test: /\.sass$/,
loaders: ['style', 'css', 'sass']
},
{
test: /\.css$/,
loaders: ['style', 'css', 'sass']
}
]
},
devServer: {
port: 3000,
historyApiFallback: true,
contentBase: './',
proxy: {
'/auth/google': {
target: 'http://localhost:5000'
},
'/api/*': {
target: 'http://localhost:5000'
}
}
}
};

A lot of times sass files can import other assets or style sheets.
// base.scss
#import 'main.scss';
body {
font: 100% Helvetica, sans-serif;
background-color: #efefef;
}
Once the page is transpiled it will look like you added multiple style sheets if that is the case.

Related

How to correctly load .otf/.tff fonts in a React app via a Webpack pipeline?

I'm having a hell of a time making this happen and it's possible the various guide I've been following are outdated or I messed something up. I know this has been a common question, and I've played with awesome font, loading it via scss, etc... and it hasn't worked, plus I found it overly complicated where the below approach is also supposed to work and more straight forward.
The webpack error (at the bottom) is thrown by css-loader which isn't the file-loader or url-loader (I tried both), so I suspect the problem is the css-loader is trying to import/find by .otf font file and can't.
If anyone has a clue, it would really help. I need to pack in the font file so my app can run offline.
Here's my file structure:
./webkacp.config.js
./src/
./fonts/AvenirLTStd-Roman.otf
./index.css
./index.jsx
Here's my webpack.config.js:
var HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require('path');
module.exports = {
mode: 'development',
module: {
rules: [
{
test: /\.jsx?$/,
loader: 'babel-loader'
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'fonts/'
}
}
],
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'images/'
}
}
],
}
]
},
resolve: {
extensions: ['.js', '.jsx'],
alias: {
'#': path.resolve(__dirname, 'src/'),
}
},
plugins: [new HtmlWebpackPlugin({
template: './src/index.html'
})],
devServer: {
historyApiFallback: true
},
externals: {
// global app config object
config: JSON.stringify({
apiUrl: 'http://127.0.0.1:4000'
})
}
}
Here's my index.css:
#font-face {
font-family: "MyFont";
src: url("./fonts/AvenirLTStd-Roman.otf") format("otf");
/* Add other formats as you see fit */
}
html, body {
font-family: 'MyFont', sans-serif;
}
Here's my index.jsx:
import React from 'react';
import { render } from 'react-dom';
import { App } from './App';
import 'bootstrap/dist/css/bootstrap.min.css';
import '#/index.css';
render(
<App />,
document.getElementById('app')
);
Finally, here's the webpack error:
ERROR in ./src/index.css (./node_modules/css-loader/dist/cjs.js!./src/index.css)
Module not found: Error: Can't resolve './fonts/AvenirLTStd-Roman.otf' in '/var/sphyrna/csdpac-services/images/csdpac-unified/frontend/src'
# ./src/index.css (./node_modules/css-loader/dist/cjs.js!./src/index.css) 4:36-76
# ./src/index.css
# ./src/index.jsx
Got it.
Two changes were needed:
Skip the urls in css-loader so it doesn't try to import/resolve the file.
Remove the san-serif in my css.
Works now. Hope this helps someone else. None of the online guides mention skipping the url.
Here's my updated css:
#font-face {
font-family: "MyFont";
src: url("./fonts/AvenirLTStd-Roman.otf") format("otf");
/* Add other formats as you see fit */
}
html, body {
font-family: 'MyFont';
}
The Webpack.config.js:
var HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require('path');
module.exports = {
mode: 'development',
module: {
rules: [
{
test: /\.jsx?$/,
loader: 'babel-loader'
},
{
test: /\.css$/,
use: [
{
loader: 'style-loader'
},
{
loader: 'css-loader',
options: {url:false}
}
]
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
use: [
{
loader: 'url-loader',
options: {
name: '[name].[ext]',
outputPath: 'fonts/'
}
}
],
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'images/'
}
}
],
}
]
},
resolve: {
extensions: ['.js', '.jsx'],
alias: {
'#': path.resolve(__dirname, 'src/'),
}
},
plugins: [new HtmlWebpackPlugin({
template: './src/index.html'
})],
devServer: {
historyApiFallback: true
},
externals: {
// global app config object
config: JSON.stringify({
apiUrl: 'http://127.0.0.1:4000'
})
}
}

Not able to import css files in react

In App.js I wanted to import App.css file or any css file. import './App.css' is not working here and giving error " ERROR in ./src/shared/App.css 1:0
Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders "
Directory Structure -
1. public
- bundle.js
2. src
- browser (folder) > index.js
- server (folder) > index.js
- server (folder) > App.js , App.css
This is my webpack.config.js file -
var path = require('path')
var webpack = require('webpack')
var nodeExternals = require('webpack-node-externals')
var combineLoaders = require('webpack-combine-loaders');
var browserConfig = {
entry: './src/browser/index.js',
output: {
path: path.resolve(__dirname, 'public'),
filename: 'bundle.js',
publicPath: '/'
},
module: {
rules: [
{ test: /\.(js)$/, exclude: /node_modules/, use: ['babel-loader']},
{
test: /\.css$/,
exclude: /node_modules/,
loader: combineLoaders([
{
loader: 'style-loader'
}, {
loader: 'css-loader',
query: {
modules: true,
localIdentName: '[name]__[local]___[hash:base64:5]'
}
},
])
}
]
},
resolve: {
extensions: ['*', '.js', '.jsx', '.css']
},
mode: 'production',
plugins: [
new webpack.DefinePlugin({
__isBrowser__: "true"
})
]
}
var serverConfig = {
entry: './src/server/index.js',
target: 'node',
externals: [nodeExternals()],
output: {
path: __dirname,
filename: 'server.js',
publicPath: '/'
},
mode: 'production',
module: {
rules: [
{ test: /\.(js)$/, exclude: /node_modules/, use: ['babel-loader']},
{
test: /\.css$/,
exclude: /node_modules/,
loader: combineLoaders([
{
loader: 'style-loader'
}, {
loader: 'css-loader',
query: {
modules: true,
localIdentName: '[name]__[local]___[hash:base64:5]'
}
}
])
}
]
},
resolve: {
extensions: ['*', '.js', '.jsx', '.css']
},
plugins: [
new webpack.DefinePlugin({
__isBrowser__: "false"
})
]
}
module.exports = [browserConfig, serverConfig]
To load CSS files in your ReactJS project, install the css-loader for ReactJS...
npm install --save-dev style-loader css-loader
Also, make sure to modify your webpack.config.js file, located in my project at: ./node_modules/webpack-dev-server/client/webpack.config.js. You'll need to add loaders, which will look something like...
module.exports = {
module: {
loaders: [
{ test: /\.js$/, exclude: /node_modules/, loaders: 'babel', query: { presets: ['react', 'es2015', 'stage-1'] } },
{ test: /\.css$/, loader: "style-loader!css-loader" }
]
},
...
}
Finally, make sure you have a resolution rule for CSS in webpack.config.js...
resolve: {
extensions: ['', '.js', '.css',...]
}

React-filepond external CSS is not being applied. I suspect it's a webpack issue

This is beating my head in. I'm using react-filepond module in my react app, but the external CSS is not being applied. The module works but has no style. I suspect it's a loader issue in webpack but I'm still learning webpack and probably missed something. Thanks!
Here are the imports as per react-filepond:
import { FilePond } from 'react-filepond';
import 'filepond/dist/filepond.css'; // located in node_modules
Here's my webpack.config.js.
I'm using webpack 3.12.0
const path = require('path');
const autoprefixer = require('autoprefixer');
const htmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
devtool: 'cheap-module-eval-source-map',
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
chunkFilename: '[id].js',
publicPath: '/'
},
resolve: {
extensions: ['.js', 'jsx', '.css']
},
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
options: {
presets: ['react']
},
exclude: /node_modules/
},
{
test: /\.css$/,
use: [
{ loader: 'style-loader' },
{
loader: 'css-loader',
options: {
importLoaders: 1,
modules: true,
localIdentName: '[name]__[local]__[hash:base64:5]'
}
},
{
loader: 'postcss-loader',
options: {
ident: 'postcss',
plugins: () => [
autoprefixer({
browsers: [
"> 1%",
"last 2 versions"
]
})
]
}
}
]
},
{
test: /\.(png|jpe?g|gif)$/,
loader: 'url-loader?limit=8000&name=images/[name].[ext]'
}
]
},
devServer: {
historyApiFallback: true
},
plugins: [
new htmlWebpackPlugin({
template: __dirname + '/src/index.html',
inject: 'body',
filename: 'index.html'
})
]
};
I found the solution for others wondering about this.
Issue: I am using CSS modules in react (note the line modules:true in the configuration of my css-loader in my webpack-config.js
The external react module I was trying to use does NOT use CSS modules.
Solution:
create a second rule for external CSS. Thus I have one for my CSS (as in the source above) and then I added this rule:
{
/* External CSS from node_modules */
test: /\.css$/,
include: /node_modules/,
loader: [
require.resolve('style-loader'),
{
loader: require.resolve('css-loader'),
options: {
importLoaders: 1,
minimize: true,
},
}
]
},
Most importantly, I did NOT turn on CSS Modules
And then, in my other CSS rule, I added:
exclude: /node_modules/,

Update UI Framework CSS for new Web Components

I'm using Grommet as a UI Framework for my React page. For web components not covered by Grommet (e.g. a web chat control) what is the easiest way to style the additional web components not covered by the Grommet CSS. Would I just add my own custom.scss?
#import "includes/colors";
#import "includes/settings";
#import "includes/card-size";
webchat {
body .wc-app, .wc-app button, .wc-app input, .wc-app textarea {
font-family: 'Segoe UI', sans-serif;
font-size: 15px;
}
...
}
In my app.js file I have the folllowing import call...
import webachatcss from '../app/custom.scss';
Then under render() I have the following code
<Chat classname='webchatcss' directLine=.... />
UPDATE: I have installed the SASS-loader and updated my webpack.config.js which now looks like this (rules section is the latest change).
var path = require('path');
var webpack = require('webpack');
module.exports = {
context: path.join(__dirname, 'app'),
entry: ['./index.html','./app.js'],
  output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js'
},
  module: {
    loaders: [
{
test: /.js?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015', 'react']
}
},
{
test: /\.html$/,
loader: "file-loader?name=[name].[ext]",
},
{
test: /\.css$/,
loader: "style-loader!css-loader"
},
{
rules: [{
test: /\.scs$/,
use: [{
loader: "style-loader"
}, {
loader: "css-loader"
}, {
loader: "sass-loader"
}]
}]
},
{
test: /\.png$/,
loader: "url-loader?limit=100000"
},
{
test: /\.jpg$/,
loader: "file-loader"
}
],
  },
resolve: {
alias: {
react: path.resolve('node_modules/react'),
},
},
devServer: {
historyApiFallback: true
}
};
The location of my error has now changed with the error now appearing in the scss (which appears to be a step closer). However I still get the error "You may need an appropriate loader to handle this file type"
You can import css files to your code and use those styles or you can create styles with react.
import '/path/to/your/css/style.css';
// and on your component
<WebChat className="webchat" />
// or
const styles = {
webchat: {
fontSize: 14,
color: '#303030'
}
};
<WebChat style={ styles.webchat } />

Load fonts with Webpack and font-face

I'm trying to load a font in my CSS file using #font-face but the font never loads. This is my directory structure.
Then in webpack.config.js I have the loader to get fonts.
var path = require('path');
var webpack = require('webpack');
module.exports = {
devtool: 'eval',
entry: [
"./index.js"
],
output: {
path: __dirname+"/build",
filename: "main.js"
},
plugins: [
new webpack.NoErrorsPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
resolve: {
extensions: ['', '.js', '.jsx']
},
module: {
loaders: [
{ test: /\.js$/, loaders: ['react-hot', 'babel-loader'], exclude: /node_modules/ },
{ test: /\.jsx?$/, loaders: ['react-hot', 'babel-loader'], exclude: /node_modules/ },
{ test: /\.svg$/, loader: "raw" },
{ test: /\.css$/, loader: "style-loader!css-loader" },
{ test: /\.(eot|svg|ttf|woff|woff2)$/, loader: 'file?name=src/css/[name].[ext]'}
]
}
};
Inside my CSS file I have this:
#font-face {
font-family: 'Darkenstone';
src: url('./Darkenstone.woff') format('woff');
}
body {
background-color: green;
font-size: 24px;
font-family: 'Darkenstone';
}
Finally, I'm calling my CSS file in my index.js with:
import './src/css/master.css';
Everything works but de font never loads.
After trying a lot of stuff the next loader made the work. Instead of file-loader, I used url-loader . You need url-loader installed.
{ test: /\.(png|woff|woff2|eot|ttf|svg)$/, loader: 'url-loader?limit=100000' }
With webpack 4 this is what solved the issue for me (diff):
{
test: /\.svg$/,
use: ['svg-loader']
},
{
test: /\.(eot|woff|woff2|svg|ttf)([\?]?.*)$/,
use: ['file-loader']
}
{ test: /\.(png|woff|woff2|eot|ttf|svg)$/, use: ['url-loader?limit=100000'] }
I had to remove svg-loader and file-loader in favor of url-loader
My app.scss file looks like this:
$fa-font-path: '~font-awesome/fonts';
#import '~font-awesome/scss/font-awesome';
$icon-font-path: "~bootstrap-sass/assets/fonts/bootstrap/";
#import '~bootstrap-sass/assets/stylesheets/bootstrap';
And in my app.js I import the app.scss:
import './app.scss';
So, after the changes, my webpack config looks like this:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpackConfig = require('./webpack.config');
module.exports = {
entry: {
app: './client/app/app.js'
},
devtool: 'source-map',
mode: 'development',
plugins: [
new HtmlWebpackPlugin({
title: 'Development',
template: 'client/index.html'
})
],
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [
{
test: /\.(sa|sc|c)ss$/,
use: [
'style-loader',
'css-loader',
'sass-loader',
],
},
{ test: /\.(png|woff|woff2|eot|ttf|svg)$/, use: ['url-loader?limit=100000'] }
]
}
};
According to Webpack's Documentation, you need to update your webpack.config.js to handle font files. See the last loader i.e.
{
test: /\.(woff|woff2|eot|ttf|otf)$/i,
type: 'asset/resource',
}
We will include all kinds of file format for webpack. The final webpack.config.js file will look something like this.
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
{
test: /\.css$/i,
use: ['style-loader', 'css-loader'],
},
{
test: /\.(png|svg|jpg|jpeg|gif)$/i,
type: 'asset/resource',
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/i,
type: 'asset/resource',
},
],
},
};
Then, you will have to import the fonts to your entry file. In this case ./src/index.js. With the loader configured and fonts in place, you can incorporate them via an #font-face declaration. The local url(...) directive will be picked up by webpack just as it was with the image.
I got some issues with my font faces when I updated from Webpack 4.x.x to latest 5.52.1
The content of my exported .woff / .woff2 / .ttf ... looked something like this:
export default __webpack_public_path__ + "glyphicons-halflings-regular.woff2";
The solution for me was to simply remove my previous file-loader entirely. It seems the files were being processed multiple times, which caused the error.
Before:
...
module: {
rules: [
{
test: /\.(png|jpg|gif|ico|woff|woff2|ttf|svg|eot)$/,
use: {
loader: 'file-loader',
options: {
name: '[name].[ext]',
useRelativePath: true
}
}
},
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
options: { url: false }
}
]
}
]
}
...
After:
...
module: {
rules: [
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
options: { url: false }
}
]
}
]
}
...
For more information: https://webpack.js.org/guides/asset-modules/
I was having the same problem.
In my case, the 'src' of the font became src="[object Module]".
Disabling esModule on webpack was the solution:
{
test: /\.(png|jpe?g|gif|svg|ttf|woff|otf)$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[contenthash].[ext]',
outputPath: 'static/img',
esModule: false // <- here
}
}
]
}
More info on it here.
This took me a little while to figure out so I'm posting here in case this helps anyone in the future.
If you're using regular css on a node js / webpack build this solution worked for me:
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: ["#babel/preset-env"],
},
},
},
{
test: /\.html$/,
exclude: /node_modules/,
use: "html-loader",
},
{
test: /\.(png|svg|jpg|jpeg|gif)$/i,
type: "asset/resource",
generator: {
filename: "assets/[name][ext][query]",
},
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/i,
type: "asset/resource",
generator: {
filename: "fonts/[name][ext][query]",
},
},
],
},
Add the import statement needed in your .js file:
// images references in the manifest
import "../../assets/icon-16.png";
import "../../assets/icon-32.png";
import "../../assets/icon-64.png";
import "../../assets/icon-80.png";
import "../../assets/icon-25.png";
import "../../assets/icon-48.png";
//fonts referenced in the css
import "../../Fonts/opensans-regular-webfont.eot";
import "../../Fonts/opensans-regular-webfont.svg";
import "../../Fonts/opensans-regular-webfont.ttf";
import "../../Fonts/opensans-regular-webfont.woff";
import "../../Fonts/opensans-regular-webfont.woff2";
import "../../Fonts/OpenSans-Regular.ttf";
Then all you need to do is update your .css file to point to the dist/fonts file created:
#font-face {
font-family: 'open_sansregular';
src: url('fonts/opensans-regular-webfont.eot');
src: url('fonts/Fonts/opensans-regular-webfont.eot?#iefix') format('embedded-opentype'), url('fonts/opensans-regular-webfont.woff2') format('woff2'), url('fonts/opensans-regular-webfont.woff') format('woff'), url('fonts/opensans-regular-webfont.ttf') format('truetype'), url('fonts/opensans-regular-webfont.svg#open_sansregular') format('svg');
font-weight: normal;
font-style: normal;
}
html,
body {
font-family: open_sansregular !important
}
And then build the project.
In the webpack.config.ts I needed two things:
Webpack will handle font files with this code
module: {
rules: [
{
test: /\.(woff|woff2|eot|ttf|otf)$/i,
type: 'asset/resource',
}
]
}
AND then I needed css-loader for webpack to understand #font-face and and url() and style-loader to inject the css into the DOM.
module: {
rules: [
{
test: /\.(woff|woff2|eot|ttf|otf)$/i,
type: 'asset/resource',
},
{
test: /\.css$/i,
use: [
'style-loader',
'css-loader'
]
},
]
}
Then in your index.css file under src add (My font was called Exo):
#font-face {
font-family: "Exo";
src: local(Exo), // This names it to use in css
url('./fonts/exo-v20-latin/exo-v20-latin-regular.woff2') format('woff2'),
url('./fonts/exo-v20-latin/exo-v20-latin-regular.woff') format('woff');
font-weight: normal;
font-style: normal;
}
html, body {
font-family: Arial, Helvetica, sans-serif;
}
I recommend woff formats because they handle all modern browsers.
Make sure to add your css file to your main app index.js:
import './index.css';
Then you might want to build so those files end up in your build/dist/public folder (whatever you've named your build folder).
npm run build
OR
yarn run build
This worked for me. Hope it works for you!
Try changing your loader to
{test: /\.(eot|svg|ttf|woff|woff2)$/, loader: 'file?name=[name].[ext]'}
and add publicPath: 'build/' to your output key.
I bumped webpack version to 4.42.0 from 4.20.2 and my code started loading the font I want.
const URL_LOADER_LIMIT = 8192
module.exports = () => ({
module: {
rules: [
{
test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
use: [
{
loader: 'url-loader',
options: {
name: '[name].[ext]',
outputPath: 'fonts/',
limit: URL_LOADER_LIMIT
}
}
]
},
{
test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
use: [
{
loader: 'url-loader',
options: {
name: '[name].[ext]',
outputPath: 'fonts/',
limit: URL_LOADER_LIMIT,
mimetype: 'application/font-woff'
}
}
]
},
{
test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
use: [
{
loader: 'url-loader',
options: {
name: '[name].[ext]',
outputPath: 'fonts/',
limit: URL_LOADER_LIMIT,
mimetype: 'application/octet-stream'
}
}
]
},
{
test: /\.mp3$/,
use: ['file-loader']
},
{
test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
use: [
{
loader: 'url-loader',
options: {
outputPath: 'images/',
name: '[name].[ext]',
limit: URL_LOADER_LIMIT,
mimetype: 'image/svg+xml'
}
}
]
},
{
test: /\.(png|jpg|gif)$/,
use: [
{
loader: 'url-loader',
options: {
outputPath: 'images/',
name: '[name].[ext]',
limit: URL_LOADER_LIMIT
}
}
]
}
]
}
})

Resources