CSS Loader in Webpack config is not working - reactjs

I am trying to integrate https://www.npmjs.com/package/react-date-range
When I import css files, it gives loader issue.
My webpack file and error message is shown below. Any help regarding this problem is appreciated
Webpack config File
var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var CircularDependencyPlugin = require('circular-dependency-plugin');
var ExtractCssChunks = require("extract-css-chunks-webpack-plugin");
var config = require('./../config');
var BASE_PATH = process.env.BASE_PATH || '/';
module.exports = {
name: 'client',
devtool: 'cheap-eval-source-map',
target: 'web',
mode: 'development',
node: { fs: 'empty' },
externals: [
{ './cptable': 'var cptable' },
{ './jszip': 'jszip' }
],
entry: {
app: [path.join(config.srcDir, 'index.js')]
},
output: {
filename: '[name].bundle.js',
chunkFilename: '[name].chunk.js',
path: config.distDir,
publicPath: BASE_PATH
},
resolve: {
modules: [
'node_modules',
config.srcDir
]
},
plugins: [
new CircularDependencyPlugin({
exclude: /a\.js|node_modules/,
failOnError: true,
allowAsyncCycles: false,
cwd: process.cwd(),
}),
new HtmlWebpackPlugin({
template: config.srcHtmlLayout,
inject: false,
chunksSortMode: 'none'
}),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('development'),
'process.env.BASE_PATH': JSON.stringify(BASE_PATH),
}),
new webpack.NamedModulesPlugin(),
new webpack.HotModuleReplacementPlugin(),
new ExtractCssChunks(),
],
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: 'babel-loader'
},
// Modular Styles
{
test: /\.css$/,
use: [
{ loader: 'style-loader' },
{
loader: 'css-loader',
options: {
modules: true,
importLoaders: 1,
}
},
{ loader: 'postcss-loader' }
],
exclude: [path.resolve(config.srcDir, 'styles')],
include: [config.srcDir]
},
{
test: /\.scss$/,
use: [
{ loader: 'style-loader' },
{
loader: 'css-loader',
options: {
modules: true,
importLoaders: 1,
}
},
{ loader: 'postcss-loader' },
{
loader: 'sass-loader',
options: {
includePaths: config.scssIncludes
}
}
],
exclude: [path.resolve(config.srcDir, 'styles')],
include: [config.srcDir]
},
// Global Styles
{
test: /\.css$/,
use: [
ExtractCssChunks.loader,
'css-loader',
'postcss-loader'
],
include: [path.resolve(config.srcDir, 'styles')]
},
{
test: /\.scss$/,
use: [
ExtractCssChunks.loader,
'css-loader',
'postcss-loader',
{
loader: 'sass-loader',
options: {
includePaths: config.scssIncludes
}
}
],
include: [path.resolve(config.srcDir, 'styles')]
},
// Fonts
{
test: /\.(ttf|eot|woff|woff2)$/,
loader: "file-loader",
options: {
name: "fonts/[name].[ext]",
}
},
// Files
{
test: /\.(jpg|jpeg|png|gif|svg|ico)$/,
loader: "file-loader",
options: {
name: "static/[name].[ext]",
}
}
]
},
devServer: {
hot: true,
contentBase: config.serveDir,
compress: true,
historyApiFallback: {
index: BASE_PATH
},
host: '0.0.0.0',
port: 3000
}
}
Following are the error messages, Seems like it can find the css files but cannot parse it, Let me know if anybody can help.
Error Message :
ERROR in ./node_modules/react-date-range/dist/styles.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
> .rdrCalendarWrapper {
| box-sizing: border-box;
| background: #ffffff;
# ./app/index.js 8:0-42
# multi ./app/index.js
ERROR in ./node_modules/react-date-range/dist/theme/default.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
> .rdrCalendarWrapper{
| color: #000000;
| font-size: 12px;
# ./app/index.js 10:0-49
# multi ./app/index.js

Since you are loading the css file from node_modules package but you set css loader with include only your source path. I suggest to either remove that:
{
test: /\.css$/,
use: [
ExtractCssChunks.loader,
'css-loader',
'postcss-loader'
],
},
Or put more package into your list, it's up to you:
{
test: /\.css$/,
use: [
ExtractCssChunks.loader,
'css-loader',
'postcss-loader'
],
include: [path.resolve(config.srcDir, 'styles'), /node_modules/\react-date-range /]
},

Related

Webpack css-loader and camelCase - How do I exclude a specific css file from being processed

I'm trying to exclude "swiper.min.css" to be excluded from processing as camelCase in my react webpack config but it keeps failing on other .css file when I do it like this.
I have tried many different options but each of them seems to lead nowhere :-(
I have tried with ternary operator, I have tried excluding based on wildcard etc - same result - it fails on all other .css files with this error:
"ERROR in ./src/pages/TimeTable/components/TimeTableLegend.module.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"
Any suggestion or pointers please?
var path = require('path');
var webpack = require('webpack');
const TerserPlugin = require("terser-webpack-plugin");
module.exports = {
optimization: {
minimize: true,
minimizer: [new TerserPlugin()],
},
entry: "./src/index.js",
output: {
path: path.resolve(__dirname, 'dist'),
filename: "bundle.min.js"
},
module: {
rules: [
{
test: /.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
},
{
test: /\.css$/,
exclude: /swiper\.min\.css$/,
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
options: {
importLoaders: 1,
modules: {
mode: (resourcePath) => {
if (/common.css$/i.test(resourcePath)) {
return 'global'
}
return 'local'
},
localIdentName: '[name]__[local]__[hash:base64:4]',
exportLocalsConvention: 'camelCase',
},
},
},
{
loader: 'postcss-loader',
},
],
test: /swiper\.min\.css$/,
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
options: {
importLoaders: 1,
modules: {
mode: (resourcePath) => {
if (/common.css$/i.test(resourcePath)) {
return 'global'
}
return 'local'
},
localIdentName: '[local]',
exportLocalsConvention: 'asIs',
},
},
},
{
loader: 'postcss-loader',
},
],
}
]
},
};

webpack Can't resolve '../../assets/icon-font/icomoon.eot?e3uwku' in 'D:\sudi\aa-Server-side-render\MAPS101_Fresh_ssr\src\scss'

I want to implement SSR in an already build react application.
I am trying to include icon-fonts and ignore CSS files from node_modules of a particular library
Please help me, I am stuck here!!
I'm trying to load a font in my SCSS file but giving the below error.
my folder structure is :
my webpack.config.js is:
const path = require('path');
const HTMLWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
module.exports = {
// webpack optimization mode
mode: ('development' === process.env.NODE_ENV ? 'development' : 'production'),
// entry files
entry: 'development' === process.env.NODE_ENV ? [
'./src/index.js', // in development
] : [
'./src/index.js', // in production
],
// output files and chunks
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'build/[name].js',
},
// module/loaders configuration
module: {
rules: [
{
test: /\.(js|jsx)$/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env', '#babel/preset-react']
}
},
exclude: [/node_modules/, /static/]
},
{
test: /\.(sa|sc|c)ss$/,
use: [
true ? 'style-loader' : MiniCssExtractPlugin.loader,
'css-loader',
'postcss-loader',
'sass-loader',
],
exclude: [/node_modules/, /static/]
},
{
test: /\.(css)$/,
use: [{
loader: MiniCssExtractPlugin.loader,
options: {
publicPath: '/public/css'
}
}, 'css-loader'],
exclude: [/node_modules/, /static/]
},
{
test: /\.(jpg|jpeg|png|svg|gif)$/,
use: [{
loader: 'file-loader',
options: {
name: '[md5:hash:hex].[ext]',
publicPath: '/public/img',
outputPath: 'img'
}
}]
},
{
test: /\.woff(\?v=\d+\.\d+\.\d+)?$/,
use: 'url-loader?limit=10000&mimetype=application/font-woff',
},
{
test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/,
use: 'url-loader?limit=10000&mimetype=application/font-woff',
},
{
test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
use: 'url-loader?limit=10000&mimetype=application/octet-stream',
},
{
test: /\.otf(\?v=\d+\.\d+\.\d+)?$/,
use: 'url-loader?limit=10000&mimetype=application/octet-stream',
},
{
test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
use: 'url-loader?limit=10000&mimetype=application/vnd.ms-fontobject',
},
]
},
// webpack plugins
plugins: [
// extract css to external stylesheet file
new MiniCssExtractPlugin({
filename: 'build/styles.css'
}),
// prepare HTML file with assets
new HTMLWebpackPlugin({
filename: 'index.html',
template: path.resolve(__dirname, 'src/index.html'),
minify: false,
}),
// copy static files from `src` to `dist`
new CopyWebpackPlugin({
patterns: [
{
from: path.resolve(__dirname, 'src/assets'),
to: path.resolve(__dirname, 'dist/assets')
}
]
}),
],
// resolve files configuration
resolve: {
// file extensions
extensions: ['.js', '.jsx', '.css', '.scss'],
},
// webpack optimizations
optimization: {
splitChunks: {
cacheGroups: {
default: false,
vendors: false,
vendor: {
chunks: 'all', // both : consider sync + async chunks for evaluation
name: 'vendor', // name of chunk file
test: /node_modules/, // test regular expression
}
}
}
},
// development server configuration
devServer: {
port: 8088,
historyApiFallback: true,
}, // generate source map
devtool: 'source-map' };
For me, I had the icomoon font in fonts directory. Did some investigation and found that the .scss file was trying to link it like this
url("./assets/styles/fonts/icomoon.svg?y2smka#icomoon"). The problem with that is icomoon.svg?y2smka#icomoon does not exist. So I looked in the fonts directory and found that it's called icomoon.eot
Solution:
In your _fonts.scss file, change all url("./assets/styles/fonts/icomoon.svg?y2smka#icomoon"). to url("./icomoon.eot")

Module parse failed: Unexpected character '#' (1:0)

I'm a really beginner in Webpack and React.
I want to use some npm (carousel multi react), but I can't. It's something wrong with my webpack.config.
Unfortunetly I can't resolve this on my own, and I saw some similiar topics, but it doesn't working for me... or I just don't know how to implement solutions in my file.
ERROR in ./node_modules/react-multi-carousel/lib/styles.css 1:0
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
const path = require("path");
const Html = require('html-webpack-plugin');
module.exports = {
entry: [
"whatwg-fetch",
"./js/index.js",
],
output: {
filename: "js/out.js",
path: path.resolve(__dirname, "build")
},
devServer: {
port: 3001,
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
}
},
{
test: /\.scss$/,
use: [
'style-loader',
'css-loader',
{
loader: "postcss-loader",
options: {
plugins: () => [
require("autoprefixer")()
],
},
},
'sass-loader',
]
},
{
test: /\.(jpg|jpeg|gif|png)$/,
use: {
loader: 'file-loader',
options: {
name: '[name].[ext]',
publicPath: 'images',
outputPath: 'images',
}
}
},
{
test: /\.(eot|ttf|woff|woff2)$/,
use: {
loader: 'file-loader',
options: {
name: '[name].[ext]',
publicPath: 'fonts',
outputPath: 'fonts',
}
}
},
]
},
plugins: [
new Html({
filename: 'index.html',
template: './index.html',
})
]
};
Try adding the below json to the rules array.
{
test: /\.(sass|less|css)$/,
loaders: ['style-loader', 'css-loader', 'less-loader']
}
Also install the required npm modules for the above loaders,
or else you can also try with adding test: /\.(sass|css)$/, to your current setup.
Thank You! It's working. ;)
{
test: /\.(sass|css|scss)$/,
use: [
'style-loader',
'css-loader',
{
loader: "postcss-loader",
options: {
plugins: () => [
require("autoprefixer")()
],
},
},
'sass-loader',
]
},
Try,
npm install --save-dev css-loader style-loader sass-loader sass webpack
Then add this code into your webpack config file,
{
test: /\.(sass|less|css)$/,
use: ["style-loader", "css-loader", 'sass-loader'],
},

electron-webpack-react error "Module parse failed: Unexpected character '#'"

I'm using Electron, Webpack and React on this project. When I try to build the project, I end up with this error:
Module parse failed: Unexpected character '#' (1:0)
You may need an appropriate loader to handle this file type.
#keyframes
The error always points to a specific .css file that is inside a node_modules folder, and the error occurs at this point:
#keyframes activeSwitchCircleAnimation {
from {
left: 0;
} to {
left: 14px; }
}
#keyframes deactiveSwitchCircleAnimation {
from {
left: 14px;
} to {
left: 0; }
}
I've already looked through a bunch of "unexpected character '#'" error questions, and most of them point towards errors occuring at .sass or .scss files, which is not the case here.
This is the webpack config file:
const webpack = require('webpack')
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const BabiliPlugin = require('babili-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const defaultInclude = path.resolve(__dirname, 'src')
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'postcss-loader'
],
include: defaultInclude
},
{
test: /(\.scss|\.sass)$/,
exclude: /node_modules/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'postcss-loader',
'sass-loader'
],
include: defaultInclude
},
{
test: /\.jsx?$/,
use: [{ loader: 'babel-loader' }],
include: defaultInclude
},
{
test: /\.(jpe?g|png|gif)$/,
use: [{ loader: 'file-loader?name=img/[name]__[hash:base64:5].[ext]' }],
include: defaultInclude
},
{
test: /\.(eot|svg|ttf|woff|woff2)$/,
use: [{ loader: 'file-loader?name=font/[name]__[hash:base64:5].[ext]' }],
include: defaultInclude
}
]
},
target: 'electron-renderer',
plugins: [
new HtmlWebpackPlugin(),
new MiniCssExtractPlugin({
filename: 'bundle.css',
chunkFilename: '[id].css'
}),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production')
}),
new BabiliPlugin()
],
stats: {
colors: true,
children: false,
chunks: false,
modules: false
}
}
Try to remove the include: defaultInclude and then put a entry point. Your webpack.config file should be like this:
const webpack = require('webpack')
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const BabiliPlugin = require('babili-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const defaultInclude = path.resolve(__dirname, 'src')
module.exports = {
entry: defaultInclude,
module: {
rules: [
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'postcss-loader'
]
},
{
test: /(\.scss|\.sass)$/,
exclude: /node_modules/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'postcss-loader',
'sass-loader'
]
},
{
test: /\.jsx?$/,
use: [{ loader: 'babel-loader' }]
},
{
test: /\.(jpe?g|png|gif)$/,
use: [{ loader: 'file-loader?name=img/[name]__[hash:base64:5].[ext]' }]
},
{
test: /\.(eot|svg|ttf|woff|woff2)$/,
use: [{ loader: 'file-loader?name=font/[name]__[hash:base64:5].[ext]' }]
}
]
},
target: 'electron-renderer',
plugins: [
new HtmlWebpackPlugin(),
new MiniCssExtractPlugin({
filename: 'bundle.css',
chunkFilename: '[id].css'
}),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production')
}),
new BabiliPlugin()
],
stats: {
colors: true,
children: false,
chunks: false,
modules: false
}
}

Using webpack to prepend variables for SCSS

Webpack amateur here... I'm trying to incorporate a theme.scss file to customize the theme used by React Toolbox by following the directions specified here, namely:
If you are using Webpack as module bundler, you are probably using sass-loader as well. What we want to do is to prepend to each SASS file compilation a bunch of variables to override and this can be done with the data option. For example:
sassLoader: { data: '#import "' + path.resolve(__dirname, 'theme/_theme.scss') + '";' }
In this case we have are prepending the theme import to each SASS compilation so the primary color will be changed in every single stylesheet.
I'm having trouble implementing this instruction with my current webpack configuration, which looks like this:
const webpack = require('webpack');
const path = require('path');
let ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
context: path.join(__dirname, 'client'),
entry: [
'./main.js',
],
output: {
path: path.join(__dirname, 'www'),
filename: 'bundle.js',
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: [
'babel-loader',
],
},
{
test: /\.css$/,
use: [
"style-loader",
{
loader: "css-loader",
options: {
modules: true,
sourceMap: true,
importLoaders: 1,
localIdentName: "[name]--[local]--[hash:base64:8]"
}
},
"postcss-loader" // has separate config, see postcss.config.js nearby
]
},
{
test: /\.scss$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
{
loader: 'css-loader', options: {
sourceMap: true,
data: '#import "' + path.resolve(__dirname, 'theme.scss') + '";'
}
},
'postcss-loader',
{
loader: 'sass-loader', options: {
sourceMap: true,
data: '#import "' + path.resolve(__dirname, 'theme.scss') + '";'
}
},
],
})
}
]
},
plugins: [
new ExtractTextPlugin({
filename: 'style.css',
allChunks: true
}),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
}),
],
resolve: {
modules: [
path.join(__dirname, 'node_modules'),
],
},
};
I don't get an error, but it seems like the data option is being entirely ignored because my file does not get imported.
Here is my theme.scss file (located in client/theme.scss):
#import "~react-toolbox/lib/colors";
$color-primary: $palette-red-500;
$color-primary-dark: $palette-red-700;
body {
background-color: black; //testing
}
I feel like I must be doing something stupid here, but I'm driving myself crazy. I have tried messing with the path of the theme.scss file (changing the data attribute to data: '#import "' + path.resolve(__dirname, 'client/theme.scss') + '";') but that doesn't make a difference. I'm surprised I'm not getting an error of some kind.
Any suggestions?
The below configuration worked for me
{
test: /\.scss$/,
include: /client/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
loader: [
{
loader: 'css-loader',
query: {
modules: true,
sourceMap: false,
localIdentName: '[name]_[local]_[hash:base64:5]',
},
},
'postcss-loader',
{
loader: 'sass-loader',
query: {
sourceMap: false,
data: `#import "${path.resolve(__dirname, 'client/_theme.scss')}";`
}
}
],
}),
},
and client/_theme.scss file
#import "react-toolbox/lib/colors.css";
$color-primary: var(--palette-blue-500);
$color-primary-dark: var(--palette-blue-700);
I checked the colors.css file in the react-toolbox library and used the same variable names. i.e --palette-blue-500, not $palette-blue-500.

Resources