Cannot import semantic-ui-css - reactjs

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)

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.

Webpack throws error for a file in node_modules

When I try to run Webpack, it throws an error:
Module parse failed: Unexpected character '#' (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
> #charset "UTF-8";
| .k-theme-test-class,
| .k-common-test-class {
# ./src/App.js 19:0-52
# ./src/index.js
# multi #babel/polyfill ./src/index.js
At first I thought the issue is the # symbol and then I realized it is not supposed to even run through node_modules, right?
My webpack.config.js is:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
// const PrettierPlugin = require('prettier-webpack-plugin');
const ESLintPlugin = require('eslint-webpack-plugin');
module.exports = {
entry: ['#babel/polyfill', './src/index.js'],
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
chunkFilename: '[id].js',
publicPath: '/',
},
devServer: {
historyApiFallback: true,
},
resolve: {
extensions: ['.js', '.jsx'],
},
module: {
rules: [
{
test: /\.js$/,
use: ['babel-loader'],
exclude: /node_modules/,
},
{
test: /\.s?css$/,
exclude: /node_modules/,
oneOf: [
{
test: /\.module\.s?css$/,
exclude: /node_modules/,
use: [
{ loader: 'style-loader' },
{
loader: 'css-loader',
options: {
modules: {
localIdentName: '[name]__[local]___[hash:base64:5]',
},
sourceMap: true,
},
},
{ loader: 'sass-loader' },
{
loader: 'postcss-loader',
options: {
postcssOptions: {
plugins: [['autoprefixer', {}]],
},
},
},
],
},
{
exclude: /node_modules/,
use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'],
},
],
},
{
test: /\.(jpe?g|png|gif|woff|woff2|eot|ttf|svg)(\?[a-z0-9=.]+)?$/,
loader: 'url-loader?limit=10000&name=img/[name].[ext]',
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: path.join(__dirname, '/src/index.html'),
filename: 'index.html',
inject: 'body',
}),
new ESLintPlugin(),
new MiniCssExtractPlugin(),
// new PrettierPlugin({
// configFile: '.prettierrc',
// }),
],
};
If I remove the 3 css-related exclude: I get the following error:
ERROR in ./node_modules/#progress/kendo-theme-default/dist/all.css
Module build failed (from ./node_modules/mini-css-extract-plugin/dist/loader.js):
ModuleBuildError: Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
SassError: Internal Error: Incompatible units: 'px' and 'em'.
at C:\www\Svila\SvilaReact\svila-erp\node_modules\webpack\lib\NormalModule.js:316:20
at C:\www\Svila\SvilaReact\svila-erp\node_modules\loader-runner\lib\LoaderRunner.js:367:11
at C:\www\Svila\SvilaReact\svila-erp\node_modules\loader-runner\lib\LoaderRunner.js:233:18
at context.callback (C:\www\Svila\SvilaReact\svila-erp\node_modules\loader-runner\lib\LoaderRunner.js:111:13)
at Object.callback (C:\www\Svila\SvilaReact\svila-erp\node_modules\sass-loader\dist\index.js:62:7)
at Object.done [as callback] (C:\www\Svila\SvilaReact\svila-erp\node_modules\neo-async\async.js:8069:18)
at options.error (C:\www\Svila\SvilaReact\svila-erp\node_modules\node-sass\lib\index.js:293:32)
# ./src/App.js 19:0-52
# ./src/index.js
# multi #babel/polyfill ./src/index.js
where the culprit is:
border-width: max( 1px, .015em );. This is invalid sass and can be generally fixed by wrapping with calc border-width: calc(max( 1px, .015em )); as mentioned here
So I have the following questions in order of importance:
Why does this file get piped through the loaders, given it has a exclude: /node_modules/?
Are files from external libraries supposed to be piped through the loaders/plugins in Webpack, or do they have another way of including themselves in the dev/production version?
Why is the .js for babel-loader excluding /node_modules/ but not s?css? (I see such tendency around random webpack.config.js files)
Interestingly enough, the culprit line margin-left: calc(24px + 1em); is actually a valid css according to World Wide Web Consortium. That makes me wonder - should a plain css be piped at all through a sass-loader? Maybe this is not entirely correct, or is it?
What is the right way to fix it?

Error while importing font or images file inside scss using Webpack 4 and react js

I am using webpack and react js.
I am getting this error when i try to import image or font file inside my scss file.
I have tried many solutions but none of them solved my problem,
webpack.common.js
enter image description here
const path = require("path");
var HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
entry: {
main: "./src/index.js",
vendor: "./src/vendor.js"
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.html$/,
use: ["html-loader"]
},
{
test: /\.(ttf|svg|png|jpg|gif)$/,
use: {
loader: "file-loader",
options: {
name: "[name].[hash].[ext]",
outputPath: "imgs"
}
}
}
]
}
};
Here is another webpack.dev.js
module.exports = merge(common, {
mode: "development",
output: {
filename: "[name].bundle.js",
path: path.resolve(__dirname, "dist")
},
plugins: [
new HtmlWebpackPlugin({
template: "./src/template.html"
})
],
module: {
rules: [
{
test: /\.scss$/,
use: [
"style-loader", //3. Inject styles into DOM
"css-loader", //2. Turns css into commonjs
"sass-loader" //1. Turns sass into css
]
}
]
}
});
ERROR in ./src/assets/index.scss (./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/lib/loader.js!./src/assets/index.scss)
Module not found: Error: Can't resolve '../../../src/assets/fonts/icomoon.ttf' in 'C:\Users\jamal\Documents\webpack-demo-app\src\assets'
# ./src/index.js
# multi (webpack)-dev-server/client?http://localhost:8080 ./src/index.js
You need to remember that the import actually takes "place" from the root index.scss file (the one that loads all the other partials). So the path you are using to fetch the asset is not accurate.
You need to use ./fonts/icomoon.ttf instead of ../fonts/icomoon.ttf
your file structure:
assets/
------/fonts
------/images
------/sass
------/---/partial1.scss // while the reference to the image is here
------/index.scss // the actual root of the reference call is here

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

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

Load images in React using webpack loader

I am unable to display images within a React component. After many trials (attempted this, this, this, this, this, this, this and this) and only errors, I am requesting for help. I'm in the development build (not production build).
I still get this error:
Module parse failed: /project/src/images/net.png Unexpected character '�' (1:0)
You may need an appropriate loader to handle this file type.
(Source code omitted for this binary file)
Component
import thumbnail from '../images/net.png';
<img src={thumbnail}/>
Webpack config:
devtool: 'cheap-module-eval-source-map',
entry: [
'eventsource-polyfill',
'webpack-hot-middleware/client',
'./src/index'
],
target: 'web',
output: {
path: path.resolve(__dirname, 'dist'),
task `npm run build`.
publicPath: 'http://localhost:3000/',
filename: 'bundle.js'
},
devServer: {
contentBase: './src'
},
plugins: [new webpack.HotModuleReplacementPlugin(), new webpack.NoEmitOnErrorsPlugin()],
module: {
rules: [
{
test: /\.js$/,
include: path.join(__dirname, 'src'),
loader: 'babel-loader'
},
{
test: /(\.css)$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: { sourcemap: true }
}
]
},
{
test: /\.(svg|png|jpg|jpeg|gif)$/,
include: './src/images',
use: {
loader: 'file-loader',
options: {
name: '[path][name].[ext]',
outputPath: paths.build
}
}
}
]
}
Directory Structure
Project
-- src
-----components
-----images
-----index.js
How can I display the image ?
Sample code here: githublink
See /src/components/home/HomePage.js
What can I do to see the image on the home page ?
Have you tried this webpack configuration
{
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader'
]
}
I am using url-loader instead.
{
test: /\.(png|jpg)$/,
use: {
loader: 'url-loader',
options: {
limit: 25000 // Max file size = 25kb
}
}
}
I am not sure. But, I think you should install it first as devDependencies e.g. yarn add -D url-loader.
test: /\.(jpe|jpg|woff|woff2|eot|ttf|svg)(\?.*$|$)/,
Try using this with your file-loader loader.
notice the (?.*$|$) instead of a plain $.
{
test: /.(png|jp(e*)g|svg|gif)$/,
use:[{
loader: 'url-loader?limit=8192'
}]
}
I loaded png with url-loader instead inside webpack. You need to rebuild webpack as well.

Resources