How to load css in react app? - css

I created a react app using create-react-app and everything works fine except that I can't figure out how to load css/stylus files.
In my previous react project that wasn't created using create-react-app I used webpack.config but now I don't know where to include this file and how to use it.
This is my folder structure:
.
+--client
| +--node_modules
| +--public
| +--src
| +--package.json
+--server
| +--node_modules
| +--src
| +--.babelrc
| +--package.json
This is my previous webpack.config.dev.js file:
import path from 'path';
import webpack from 'webpack';
export default {
entry: [
'webpack-hot-middleware/client?reload=true',
path.join(__dirname, '/client/index.js')
],
output: {
filename: 'bundle.js',
path: '/',
publicPath: '/'
},
plugins: [
new webpack.NoEmitOnErrorsPlugin(),
new webpack.HotModuleReplacementPlugin()
],
module: {
rules: [
{
test: /\.js$/,
include: path.join(__dirname, 'client'),
loader: 'babel-loader',
},
{
test: /\.styl$/,
use: [
'style-loader',
'css-loader',
{
loader: 'stylus-loader',
},
],
},
{
test: /\.css?$/,
use: [
'style-loader',
{
loader: 'css-loader',
},
],
},
],
},
resolve: {
extensions: [ '.js', '.styl' ]
}
}
Please let me know if I need to provide additional information.

There is detailed informations about how to add SCSS and Less files to create-react-app project on their documentation. You can check here for more detail.
You can add basic CSS styling with just importing the file like shown below;
import '/css/main.css';
Or you can add as classNames
const styles = {
header: {
fontSize: 18,
color: '#909090',
}
};
export default class Header extends React.Component {
render() {
return (
<h1 className={styles.header}>This is a header</h1>
);
}
}

One of the approaches involves loading CSS files (via css-loader) from your JS files, for a Text.jsx
import React from 'react';
import './screen.css'; // if screen.css is located next to Text.jsx
class Text extends React.Component {
// ...
}
export default Text;
You could also generate an output CSS, using e.g. ExtractTextPlugin (see Webpack2 loading and extracting LESS file)

Related

TailwindCSS 3.0 Upgrade overriding button styles

Problem:
Button class being overridden by default tailwind base classes. Not sure why my classes on the element aren't being applied.
Question:
How can I get my styles to apply properly?
Screenshot:
As you can see background color on .documentCategory__row is being overridden by button, [type=button] on index.scss which is being defined within #tailwind/base.
/* index.scss */
:root {
--color-primary: #00a3e0;
--color-secondary: #470a68;
--color-success: #87d500;
--color-accent: #e87722;
/* Dark themes below */
--color-dark-primary: rgba(31, 41, 55, 1);
--dark-text: rgba(187, 193, 198, 1);
}
#import "tailwindcss/base";
#import "tailwindcss/components";
#import "tailwindcss/utilities";
I'm not sure if this has to do with me switching to dart-scss so here is my webpack configuration in case I am missing something
import path from 'path'
import { Configuration as WebpackConfiguration, HotModuleReplacementPlugin } from 'webpack'
import { Configuration as WebpackDevServerConfiguration } from 'webpack-dev-server';
import HtmlWebpackPlugin from 'html-webpack-plugin'
import ForkTsCheckerWebpackPlugin from 'fork-ts-checker-webpack-plugin'
import ESLintPlugin from 'eslint-webpack-plugin'
import tailwindcss from 'tailwindcss'
import autoprefixer from 'autoprefixer'
const CopyPlugin = require('copy-webpack-plugin');
interface Configuration extends WebpackConfiguration {
devServer?: WebpackDevServerConfiguration;
}
const config: Configuration = {
mode: 'development',
devServer: {
static: path.join(__dirname, 'build'),
historyApiFallback: true,
port: 4000,
open: true,
hot: true,
},
output: {
publicPath: '/',
},
entry: './src/index.tsx',
module: {
rules: [
{
test: /\.(ts|js)x?$/i,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
'#babel/preset-env',
'#babel/preset-react',
'#babel/preset-typescript',
],
},
},
},
{
test: /\.(sa|sc|c)ss$/i,
use: [
'style-loader',
'css-loader',
'sass-loader',
{
loader: 'postcss-loader', // postcss loader needed for tailwindcss
options: {
postcssOptions: {
ident: 'postcss',
plugins: [tailwindcss, autoprefixer],
},
},
},
],
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
loader: 'file-loader',
options: {
outputPath: '../fonts',
},
},
],
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
},
plugins: [
new HtmlWebpackPlugin({
template: 'public/index.html',
}),
new HotModuleReplacementPlugin(),
new CopyPlugin({
patterns: [
// relative path is from src
{ from: 'public/images', to: 'images' },
],
}),
// Add type checking on dev run
new ForkTsCheckerWebpackPlugin({
async: false,
}),
// Add lint checking on dev run
new ESLintPlugin({
extensions: ['js', 'jsx', 'ts', 'tsx'],
}),
],
devtool: 'inline-source-map',
};
export default config
If there are other files I am missing that are needed let me know!
without seeing what your index.tsx looks like I can only make a guess, but here's what caused this issue in our app:
in our index.tsx we were importing index.css after importing our component tree with import App from 'src/App. thus the css was loaded into the site in the wrong order. imports from components first (css modules, normal css imports), tailwind last.
go to your entry file (probably index.tsx) and try moving your import 'index.scss' line above importing the root component.
like this for example
/* index.tsx */
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css'; // this file holds all tailwind styles
import { App } from 'src/App';
// ...
read more here:
https://github.com/tailwindlabs/tailwindcss/discussions/7304#discussioncomment-2256226
Even i faced the same issue but I am using Vue3 + element-ui-plus, after spending more than 6 hours my solution is to set :native-type='null':
<el-button type='primary' round #click='handleClick' :native-type='null'>Click Me</el-button>
but this is kinda "hack", this either need to be fixed by Tailwind or by element-ui team. Anyhow, for now enjoy ;)
And the discussion is on here
I got the same issue using tailwindcss v3 and NextUI, and button's background were "transparent". By adding type = {null}, to button's I solve the issue

Css is not used by jsx in ReactJS

I use ReactJS with Webpack and TypeScript.
I'm trying to include CSS with React. But my CSS is not use by my React application.
I created a global.d.ts file to declare my css module. I imported my css into my.tsx file but when I add a class to an element, nothing works.
I have already tried to install a css module but I didn't succeed. So, I just made the solution to create a global.d.ts file
global.d.ts :
declare module '*.css';
Hello.tsx
import * as css from './Hello.css';
export interface HelloProps {
compiler: string;
framework: string;
}
export class Hello extends React.Component<HelloProps, {}> {
render() {
return (
<form>
<p className={css.test}> Test </p>
</form>
);
}
}
Hello.css
.test {
color: red;
}
webpack.config.js
module: {
rules: [
.....
{ test: /\.css$/, exclude: /node_modules/, use: ['style-loader', 'css-loader'] }
]
},
The word "test" is written in black.
When it should be in red
This would be due to you not having modules set to true in your css-loader options.
// webpack.config.js
rules: [
{
test: /.css$/,
exclude: /node_modules/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
modules: true,
},
},
],
},
],
Also, i would just do the following as there's no need for the * import.
import css from './Hello.css'
and then in your jsx:
<Component className={css.test} />
im quite new to react but i think if you remove:
"import * as css from './Hello.css';" And Replace it with "import './Hello.css';"

How to edit webpack to use SCSS in React app?

I created a new React app with create-react-app (using React ver. 16.6.3). Now I want to use SCSS for my components. So first I ran the eject script. Then in webpack.config.dev.js I did the following edit:
{
test: cssRegex,
exclude: cssModuleRegex,
use: getStyleLoaders({
importLoaders: 1,
modules: true,
localIdentName: '[name]__[local]__[hash:base64:5]'
}),
}
I also installed node-sass package.
Then I created my Test .scss file:
.Test {
background-color: gold;
.Header {
color: lighten(purple, 20%);
}
}
And my Test component with importing the .scss file
import React from 'react';
import style from './test.scss';
const Test = (props) => (
<div className={style.Test}>
This is div1
<div className={style.Header}>Div 2</div>
</div>
);
export default Test;
That didn't work and I didn't see any styling. I tried to import the .scss directly and use it:
import './test.scss';
...
<div className='Test'>
This is div1
<div className={style.Header}>Div 2</div>
</div>
...
That did work and I saw the styling on the div with className='Test'.
I tried to change the webpack as follows:
const CSSModuleLoader = {
loader: 'css-loader',
options: {
modules: true,
sourceMap: true,
localIdentName: '[local]__[hash:base64:5]',
minimize: true
}
}
const CSSLoader = {
loader: 'css-loader',
options: {
modules: false,
sourceMap: true,
minimize: true
}
}
const postCSSLoader = {
loader: 'postcss-loader',
options: {
ident: 'postcss',
sourceMap: true,
plugins: () => [
autoprefixer({
browsers: ['>1%', 'last 4 versions', 'Firefox ESR', 'not ie < 9']
})
]
}
}
...
{
test: /\.scss$/,
exclude: /\.module\.scss$/,
use: ['style-loader', CSSLoader, postCSSLoader, 'sass-loader']
},
{
test: /\.module\.scss$/,
use: [
'style-loader',
CSSModuleLoader,
postCSSLoader,
'sass-loader',
]
},
At first I got an autoprefixer not defined error. I imported it with const autoprefixer = require('style-loader') - that made this error disappear, though I'm still not convinced that was the correct require and correct fix.
But then I got the following error:
Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
- configuration.module.rules[2].oneOf[0].use should be one of these:
non-empty string | function | object { loader?, options?, ident?, query? } | function | [non-empty string | function | object { loader?, options?, ident?, query? }]
-> Modifiers applied to the module when rule is matched
Details:
* configuration.module.rules[2].oneOf[0].use should be a string.
* configuration.module.rules[2].oneOf[0].use should be an instance of function
* configuration.module.rules[2].oneOf[0].use should be an object.
* configuration.module.rules[2].oneOf[0].use should be an instance of function
* configuration.module.rules[2].oneOf[0].use[1] should be a string.
* configuration.module.rules[2].oneOf[0].use[1] should be an instance of function
* configuration.module.rules[2].oneOf[0].use[1] has an unknown property 'loaders'. These properties are valid:
object { loader?, options?, ident?, query? }
Don't know how to deal with that...
How do I configure webpack to either immediately compile .scss to .css in the same directory (that way I can import .css and use it regularly with style.Class) or to use the .scss import in my file in the same manner and later compile it to .css for production?
Please use below rules in webpack file and remove extra code.
rules: [
{
test: /\.s?css$/,
use: [
'style-loader',
'css-loader',
'sass-loader'
]
}
]

unable to load css in react js

my all css files placed under src/assets/css/* and i am trying to import or load css file inside my component, i have tried to load css with below webpack configuration
Webpack file
{ test: /\.css$/, loader: "style-loader!css-loader" }
Component
import './../../assets/css/bootstrap.min.css';
Also tried to load css in index.html file like <link rel="stylesheet" href="/src/assets/css/bootstrap.min.css">
Also, is there a way if i have 5-6 css files by which i dont need to load all files in every component like if we can add in <head> tag
Here is my webpack.config file. I have used foundation instead of bootstrap but the webpack configuration is similar.
var webpack = require('webpack');
var path = require('path');
module.exports = {
entry: [
'script!jquery/dist/jquery.min.js',
'script!foundation-sites/dist/js/foundation.min.js',
'./app/app.jsx'
],
externals: {
jquery: 'jQuery'
},
plugins:[
new webpack.ProvidePlugin({
'$': 'jquery',
'jQuery': 'jquery'
})
],
output: {
path: __dirname,
filename: './public/bundle.js'
},
resolve: {
root: __dirname,
modulesDirectories: [
'node_modules',
'./app/components',
'./app/api'
],
alias: {
applicationStyles: 'app/styles/app.scss',
actions: 'app/actions/actions.jsx',
reducers: 'app/reducers/reducers.jsx',
configureStore: 'app/store/configureStore.jsx'
},
extensions: ['', '.js', '.jsx']
},
module: {
loaders: [
{
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'stage-0']
},
test:/\.jsx?$/,
exclude: /(node_modules|bower_components)/
}
]
},
sassLoader:{
includePaths: [
path.resolve(__dirname, './node_modules/foundation-sites/scss')
]
},
devtool: 'cheap-module-eval-source-map'
};
And yes you can bundle the css in one file with webpack and import it in the root component.
Check my github repo for more details- https://github.com/hmachaharywork/ReactTodo
Use Extract text plugin. Only import this plugin in your webpack.conf.js
const ExtractTextPlugin = require("extract-text-webpack-plugin");
and refactor your rule like:
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: "css-loader"
})
}
Finally, push new instance in plugin list:
plugins: [
new ExtractTextPlugin("styles.css"),
]

How to import css file for into Component .jsx file

I am trying to use the react-day-pickers component like so but I can't figure out how to import the .css file and I keep getting the error:
Module parse failed:
/Users/qliu/Documents/workspace/AppNexus/pricing_ui/contract-ui/app_contract-ui/node_modules/react-day-picker/lib/style.css Unexpected token (3:0)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (3:0)
I have "css-loader": "^0.19.0", in my package.json installed and
here is my Calender.jsx file:
import React from "react";
import DayPicker, { DateUtils } from "react-day-picker";
import "../../../node_modules/react-day-picker/lib/style.css"; // <==== ERROR ON THIS LINE
export default class Calender extends React.Component {
state = {
selectedDay: null
};
handleDayClick(e, day, modifiers) {
if (modifiers.indexOf("disabled") > -1) {
console.log("User clicked a disabled day.");
return;
}
this.setState({
selectedDay: day
});
}
render() {
// Add the `selected` modifier to the cell of the clicked day
const modifiers = {
disabled: DateUtils.isPastDay,
selected: day => DateUtils.isSameDay(this.state.selectedDay, day)
};
return <DayPicker enableOutsideDays modifiers={ modifiers } onDayClick={ this.handleDayClick.bind(this) } />;
}
}
and this is my webpack.config.js:
var path = require('path');
var webpack = require('webpack');
var settings = require('./src/server/config/settings');
var LessPluginAutoPrefix = require('less-plugin-autoprefix');
module.exports = {
devtool: '#source-map',
resolve: {
extensions: ['', '.jsx', '.js']
},
entry: [
'webpack-hot-middleware/client',
'./src/client/index.jsx'
],
externals: {
'react': 'React',
'react-dom': 'ReactDOM',
// to avoid duplicate import of React with react-addons-css-transition-group
'./React': 'React',
'./ReactDOM': 'ReactDOM',
config: 'config'
},
output: {
path: path.join(__dirname, 'public'),
filename: 'bundle.js',
publicPath: '/'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
lessLoader: {
lessPlugins: [
new LessPluginAutoPrefix({ browsers: ['last 2 versions'] })
]
},
module: {
loaders: [{
test: /\.(js|jsx)$/,
loaders: ['babel'],
exclude: /node_modules/
},
{
test: /\.less$/,
loader: 'style!css!less'
},
{
test: /\.json$/,
loader: 'json-loader'
}]
}
};
How are you compiling this? If it's webpack, you'd probably need to bring in the style-loader and include something like this in the module.loaders array in your webpack config:
{
test: /\.css$/,
loader: "style!css"
}
Update: With the webpack.config.js now provided, we can confirm it needed a change in the module.loaders array. OP was using a less loader and only checking for .less files, so the exact loader object should read:
{
test: /\.(less|css)$/,
loader: 'style!css!less'
}
As suggested by #Q Liu. Leaving the original bit as if someone comes here with an error importing a .css file, it's likely what they need.
I used the following in my webpack config and it worked:
test: /\.css$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
modules: true,
},
},
],
JSX is not CSS. In your main HTML file, just add a <link> element to the CSS file, and the DOM generated by React will use it.

Resources