How to properly load CSS from an external module in React? - reactjs

In my react.js app I am trying to use an external module (React Toastify)
using the following statement:
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
Unfortunately this throws the following error:
Uncaught Error: Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type.
> .Toastify__toast-container {
| z-index: 9999;
I guess it has something to do with webpack, here are my settings in webpack.config.js:
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'assets'),
},
devtool: production ? '' : 'source-map',
resolve: {
extensions: [".js", ".jsx", ".json"],
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
},
],
},
};
I am not sure how this can be fixed, any advice appreciated.

In your webpack config file you have add the css loader test:
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
}, {
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},
],
},
And don't forget to install it with npm i -D css-loader.
More info here: https://github.com/webpack-contrib/css-loader

Related

React/TypeScript unexpected token

I'm building out a react/TS app and am running into this compiler error. I'm sure it's a config issue, but alas, I can't figure out which config. I'm not sure if it has to do with the generic specifically, or if I will see the "unexpected token" error show up in other circumstances as well.
ERROR in ./src/App.tsx
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: /Users/.../src/App.tsx: Unexpected token (15:4)
13 | const [coordinates, setCoordinates] = useState<
14 | CoordinatesQueryType | undefined
> 15 | >();
| ^
16 |
Webpack config follows. FWIW I added "react" to module.rule.options, but then i got another error that said I was missing "babel-preset-react", installed that, then another error, and then didn't wanna go down the rabbit hole.
const path = require("path");
const webpack = require("webpack");
module.exports = {
entry: "./src/index.tsx",
mode: "development",
module: {
rules: [
{
test: /\.(js|jsx|ts|tsx)$/,
exclude: /(node_modules|bower_components)/,
loader: "babel-loader",
options: { presets: ["#babel/env"] }
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"]
}
]
},
resolve: { extensions: ["*", ".js", ".jsx", ".ts", ".tsx"] },
output: {
path: path.resolve(__dirname, "dist/"),
publicPath: "/dist/",
filename: "bundle.js"
},
devServer: {
port: 4000,
hot: true
},
plugins: [new webpack.HotModuleReplacementPlugin()]
};
And babel.rc:
{
"presets": ["#babel/env", "#babel/preset-react", "#babel/preset-flow"],
"plugins": ["#babel/plugin-transform-runtime"]
}
Is there any setup for typescript?
I think you are missing this in babel presets:
#babel/preset-typescript
And also I can't see any ts-loader in your webpack config. So you would not get typechecking even though you compile typescript. To fix this:
Change current rule for babel to match only js files
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /(node_modules|bower_components)/,
loader: "babel-loader",
options: { presets: ["#babel/env"] }
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"]
}
]
},
Install necessary tools:
yarn add -D #babel/preset-typescript ts-loader
Add #babel/preset-typescript to babel.rc presets.
Add ts-loader to webpack.config.js module rules.
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /(node_modules|bower_components)/,
loader: "babel-loader",
options: { presets: ["#babel/env"] }
},
// Typescript loader
{
test: /\.(ts|tsx)$/,
exclude: /node_modules/,
use: ["ts-loader"],
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"]
}
]
},
I think this should be able to fix the problem.
Also, you are having both options\presets and .babelrc, try to use only one of these for configuration.

Prefix React className

So, I need to prefix my react components classNames so it doesn't conflict with global classes.
And no, I can't use CSS modules because of how my yarn workspaces are built
So, if I have a button class I would like it to become my_app-button
<button className="button">Hello StackOverflow</button>
to
<button className="my-app_button">Hello StackOverflow</button>
PostCSS does that for me in the CSS part, but on the React Side I wasn't able to find a solution
All of my components use typescript
I've tried using a webpack loader to do the job, and it did! But only on my Storybook server, when I used it with my separate webpack config it didn't work
The only error that is given to me is invariant 85
This is my Webpack Config, alongside the webpack loader and the babel-loader
import { Configuration, ProgressPlugin } from 'webpack'
const config: Configuration = {
mode: 'production',
entry: './src/index.ts',
target: 'node',
output: {
filename: '[name].js',
path: __dirname + '/dist',
publicPath: '',
},
resolve: {
extensions: ['.js', '.jsx', '.ts', '.tsx'],
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
presets: ['#babel/preset-react', '#babel/preset-env', 'minify'],
},
},
],
},
{
test: /\.tsx?$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
presets: [
'#babel/preset-react',
'#babel/preset-env',
'#babel/preset-typescript',
'minify',
],
},
},
],
},
{
test: /\.tsx$/,
exclude: /node_modules/,
use: [
{
loader: 'react-classname-prefix-loader?prefix=giffy_css',
},
],
},
{
test: /\.(png|jpe?g|gif)$/,
exclude: /node_modules/,
use: [{ loader: 'file-loader' }],
},
],
},
plugins: [new ProgressPlugin()],
}
export default config
and just in case you need it, this is my Storybook webpack configuration
webpackFinal: async (config, { configType }) => {
config.module.rules.push({
test: /\.tsx$/,
exclude: /node_modules/,
use: [
{
loader: 'react-classname-prefix-loader?prefix=giffy_css',
},
],
})
// console.log(config.module.rules[0].use[0].options.overrides[0])
return config
}
i have also tried first compiling my components with babel and then using webpack
i tried searching for an equivalent webpack loader in babel, but could not find it

Module parse failed: Unexpected character '�' (1:0) You may need an appropriate loader to handle this file type

I am using styleguidist for my react application, here is the code of my styleguid.config.js file:
module.exports = {
webpackConfig: {
module: {
rules: [
// Babel loader, will use your project’s .babelrc
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader'
},
// Other loaders that are needed for your components
{
test: /\.css$/,
loader: 'style-loader!css-loader?modules'
}
]
}
}
}
Now I want to show barcode image in my styleguidist server which is running in http://localhost:6060.
Code of my styleguidist readme.md
```jsx
var Macybarcode = require('../../../containers/assets/img/macy/barcode.png');
const barcode_img = Macybarcode;
const barcode_no = "33527111690008";
<BarcodeMacy1 imgString={barcode_img} lineString={barcode_no} paddingTop="20px" width="50%" height="40px" />
```
But whenever I am trying to show image my server is giving following error:
Please click to see the Error console
You need url-loader for images
Use:
npm install url-loader --save
module.exports = {
webpackConfig: {
module: {
rules: [
// Babel loader, will use your project’s .babelrc
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader'
},
// Other loaders that are needed for your components
{
test: /\.css$/,
loader: 'style-loader!css-loader?modules'
},
{
test: /\.(jpg|png|svg)$/,
use: {
loader: 'url-loader',
options: {
limit: 25000
}
}
}
]
}
}
}
try this line inside
{ test: /\.(png|woff|woff2|eot|ttf|svg)$/, loader: 'url-loader?limit=100000' }

Style css module not applied [React + Webpack]

I am discovering the CSS modules in a react application, I also use Webpack.
I edit the webpack configuration file, I try to change the color of a paragraph using a css file to test but the style is not applied.
Visual studio code tells me that the module is not found but I have yet entered the correct path of the file.
I think it's a problem with the webpack configuration file.
I did a lot of research, I tried different solutions ...
I thank you in advance for your help and your answers
I tried to follow the tutorial of this site => https://javascriptplayground.com/css-modules-webpack-react/
I did research on stack overflow, I try several solutions proposed in the different posts but it still does not work.
I then check with the webpack documentation to add the loaders "style-loader" and "css-loader"
Webpack configuration file
module.exports = {
entry: [
'./src/index.js'
],
output: {
path: __dirname,
publicPath: '/',
filename: 'bundle.js'
},
module: {
rules: [
{
enforce: 'pre',
test: /\.js$/,
loader: 'standard-loader',
exclude: /node_modules/
}, {
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
}, {
test: /\.css$/,
use: ['style-loader', 'css-loader' ]
}
],
loaders: [{
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['react', 'es2015', 'stage-1']
}
},{
test: /\.css$/,
loader: "style-loader!css-loader"
}
]
},
resolve: {
extensions: ['', '.js', '.jsx','css']
},
devServer: {
historyApiFallback: true,
contentBase: './'
}
};
File CSS
.title {
color: yellow;
font-size: 124px;
}
Test code snippet
import styles from './home.css';
<p className={styles.title}>hello world</p>
I want to change the color of a paragraph, using a CSS module but the style does not apply to the refresh of the page.

Cannot import semantic-ui-css

when I import the semantic ui react css module in my index.js file I get the following error.
ERROR in ./~/semantic-ui-css/themes/default/assets/fonts/brand-icons.svg
Module parse failed: C:\Users\dimal\Documents\Work\sample-app\node_modules\semantic-ui-css\themes\default\assets\fonts\brand-icons.svg Unexpected token (1:0)
You may need an appropriate loader to handle this file type.
| <?xml version="1.0" standalone="no"?>
| <!--
| Font Awesome Free 5.0.8 by #fontawesome - https://fontawesome.com
# ./~/css-loader!./~/semantic-ui-css/semantic.min.css 7:196806-196862
# ./~/semantic-ui-css/semantic.min.css
# ./src/index.js
My webpack config is as following
var path = require('path');
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'build'),
filename: 'index.js',
libraryTarget: 'commonjs2'
},
module: {
rules: [{
test: /\.js$/,
include: path.resolve(__dirname, 'src'),
exclude: /(node_modules|bower_components|build)/,
use: {
loader: 'babel-loader',
options: {
presets: ['env']
}
}
},{
test: /\.(css|less)$/,
use: ["style-loader", "css-loader", "less-loader"]
}]
},
externals: {
'react': 'commonjs react'
}
};
What am I doing wrong in this?
The semantic UI CSS file has references to other files like images and fonts, so webpack has to have loaders for those types of files as well.
Ensure you have url-loader and file-loader packages installed and add these loaders to your webpack config:
{
test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
loader: require.resolve("url-loader"),
options: {
limit: 10000,
name: "static/media/[name].[hash:8].[ext]",
},
},
{
test: [/\.eot$/, /\.ttf$/, /\.svg$/, /\.woff$/, /\.woff2$/],
loader: require.resolve("file-loader"),
options: {
name: "/static/media/[name].[hash:8].[ext]",
},
}
(you can change the folder path as you desire)

Resources