Webpack not picking up imports of scss files in react components - reactjs

I want to set up my react project with an scss file for each component. So given a component called PermissionPicker I want to import a PermissionPicker.scss in the jsx file.
With my current set up the webpack loaders are only loading scss files when imported in my entry point (boot-client.tsx). import './PermissionPicker.scss' in my PermissionPicker components causes a webpack error:
Module parse failed: PermissionPicker.scss Unexpected token (1:1)
You may need an appropriate loader to handle this file type.
I was under the impression that I could import scss anywhere in my project similar to how create-react-app works.
Any advice would be great!
Below is my webpack config.
const sharedConfig = () => ({
stats: { modules: false },
resolve: { extensions: [ '.js', '.ts', '.tsx', '.jsx' ] },
output: {
filename: '[name].js',
publicPath: '/dist/' /
},
module: {
rules: [
{ test: /\.tsx?$/, include: /client/, use: 'babel-loader' },
{ test: /\.tsx?$/, include: /client/, use: 'awesome-typescript-loader?silent=true' }
]
},
plugins: [new CheckerPlugin()]
});
const clientBundleOutputDir = './wwwroot/dist';
const clientBundleConfig = merge(sharedConfig(), {
entry: { 'main-client': './client/boot-client.tsx' },
module: {
rules: [
{ test: /\.css$/, use: ExtractTextPlugin.extract({ use: 'css-loader' }) },
{ test: /\.scss$/, use: ExtractTextPlugin.extract({
use: [{
loader: "css-loader"
}, {
loader: "sass-loader"
}],
fallback: "style-loader"
})
},
{ test: /\.(png|jpg|jpeg|gif|svg)(\?\S*)?$/, use: 'url-loader?limit=25000' }
]
},
output: { path: path.join(__dirname, clientBundleOutputDir) },
plugins: [
new ExtractTextPlugin('site.css'),
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./wwwroot/dist/vendor-manifest.json')
})
].concat(isDevBuild ? [
new webpack.SourceMapDevToolPlugin({
filename: '[file].map',
moduleFilenameTemplate: path.relative(clientBundleOutputDir, '[resourcePath]')
})
] : [
])
});

You need to install node-sass with sass-loader, because the sass-loader requires node-sass as peerDependency
npm install sass-loader node-sass --save-dev
And missing something as include: join(__dirname, 'src')
rules: [
{
test: /\.css$/,
include: join(__dirname, 'src'),
use: ExtractTextPlugin.extract({ use: 'css-loader' })
},
{
test: /\.scss$/,
include: join(__dirname, 'src'),
use: ExtractTextPlugin.extract({
use: [{
loader: "css-loader"
}, {
loader: "sass-loader"
}],
fallback: "style-loader"
})
},
{ test: /\.(png|jpg|jpeg|gif|svg)(\?\S*)?$/, use: 'url-loader?limit=25000' }
]
The src is a common path for Components, you need to indicate the path from the path of your config file

Related

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)

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'],
},

Webpack 4 configuration for react-toolbox

I try to upgrade my app from webpack 2 to webpack 4.16.5.
Because I want not again end up in a hard to understand some hundreds line config, I start with a minimal config. This is my current:
const path = require("path");
const HtmlWebPackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const context = path.resolve(__dirname, "app");
module.exports = {
entry: {
home: "./index.js"
},
context,
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.html$/,
use: [
{
loader: "html-loader",
options: { minimize: true }
}
]
},
{
test: /\.(css|sass|scss)$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: "css-loader"
},
{
loader: "postcss-loader"
},
{
loader: "sass-loader"
}
]
}
]
},
plugins: [
new HtmlWebPackPlugin({
template: "./index.html",
filename: "./index.html"
}),
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css"
})
],
resolve: {
extensions: [".js", ".jsx", ".css", "json"],
modules: [path.resolve(__dirname, "node_modules"), context]
}
};
But I run in problems importing the CSS files from react-toolbox i.e.:
import Dialog from 'react-toolbox/lib/dialog';
in a js file and also
#import "react-toolbox/lib/button/theme.css";
causes errors like this:
ERROR in ../node_modules/react-toolbox/lib/switch/theme.css (../node_modules/css-loader!../node_modules/postcss-loader/src!../node_modules/sass-loader/lib/loader.js!../node_modules/react-toolbox/lib/switch/theme.css)
Module build failed (from ../node_modules/css-loader/index.js):
Error: composition is only allowed when the selector is single: local class name not in ".disabled", ".disabled" is weird
Does anyone have a working application with wbpack4 and react-toolbox? Also, any hints on what may cause these errors are welcome!
I'm learning react.js with the js stack from scratch tutorial and try to using react-toolbox components.
Finnaly, i have a working demo with webpack 4 and the react-toolbox, it's based on the react-toolbox-example.
This is my settings:
add css-modules related packages
$ npm install postcss postcss-cssnext postcss-import postcss-loader css-loader style-loader
add a postcss.config.js
module.exports = {
plugins: {
'postcss-import': {
root: __dirname,
},
'postcss-cssnext': {}
},
};
add a webpack rule
...
{ test: /\.css$/, use: [
'style-loader',
{
loader: 'css-loader',
options: {
modules: true,
sourceMap: true,
importLoaders: 1,
localIdentName: '[name]--[local]--[hash:base64:8]'
}
},
'postcss-loader'
]},
...
add cmrh.conf.js - Using the css-modules-require-hook for SSR(Optional)
module.exports = {
generateScopedName: '[name]--[local]--[hash:base64:8]'
}
You can see all the settings in here, hope it will work for you.

Using Grommet with ReactJS webpack and scss import Issue

I am trying to use grommet in my React Project and i am using webpack. I have added the scss loader and when i build my app i am getting the following error:
ERROR in ./~/css-loader!./~/sass-loader!./scss/index.scss
Module build failed:
#import "inuit-defaults/settings.defaults";
^
File to import not found or unreadable: inuit-defaults/settings.defaults
Parent style sheet: /Users/hduser/sample-app/node_modules/grommet/scss/grommet-core/_settings.scss
in /Users/hduser/sample-app/node_modules/grommet/scss/grommet-core/_settings.scss (line 2, column 1)
# ./scss/index.scss 4:14-116 13:2-17:4 14:20-122
Not sure what i am doing wrong..
Here is my webpack.config.js
var webpack = require('webpack');
var path = require('path');
module.exports ={
devtool :'cheap-module-eval-source-map',
entry:[
'webpack/hot/only-dev-server',
'./index.jsx'
],
module:{
loaders:[
{
test: /\.jsx?$/,
exclude :/node_modules/,
include: __dirname,
loader:'react-hot'
},
{
test: /\.jsx?$/,
exclude :/node_modules/,
include: __dirname,
loader:'babel',
query:{
"plugins":["transform-decorators-legacy"],
"presets":["es2015","react"]
}
},
{
test :/\.css?$/,
include: __dirname,
loaders :['style','css']
},
{
test: /\.less$/,
loader: "style!css!less"
},
{
test: /\.json$/,
loader: "json"
},
{
test: /\.scss$/,
loaders: ["style", "css", "sass"]
}
]
},
resolve:{
extensions:['','.js','.jsx']
},
output:{
path: __dirname+'/',
publicPath:'/',
filename:'bundle.js'
},
devServer:{
contentBase: './',
hot:true
},
plugins: [
new webpack.HotModuleReplacementPlugin()
,new webpack.NoErrorsPlugin()
]
}
Update
if u use npm3+ you can simply do this(see alan's explanation here):
{
test: /\.scss$/,
loader: 'style!css!sass?outputStyle=expanded&' +
'includePaths[]=' +
(encodeURIComponent(path.resolve('./node_modules')))
},
or write scss loader like this:
{
test: /\.scss$/,
loader: "style!css!sass?OutputStyle=expaned&" +
'includePaths[]=' +
(encodeURIComponent(
path.resolve(process.cwd(), './node_modules')
)) +
'&includePaths[]=' +
(encodeURIComponent(
path.resolve(process.cwd(),
'./node_modules/grommet/node_modules'))
)
}
I had the same issue, and got this working by this way:
var ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
// ...
module: {
loaders: [
// ...
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract('css!sass')
}
]
},
sassLoader: {
includePaths: [ './node_modules' ]
},
plugins: [
new ExtractTextPlugin('public/grommet.css', {
allChunks: true
})
]
}
But remember to import the generated css file into your index.html
I fixed it by following Webpack 2 conventions.
{
test: /(\.scss$)/,
loaders: [{
loader: 'style-loader'
}, {
loader: 'css-loader'
}, {
loader: 'sass-loader',
options: {
outputStyle: 'compressed',
includePaths: ['./node_modules']
}
}]
}
Working quite well on my side!
Use the following scss loader in webpack config (thanks to https://github.com/primozs)
{
test: /\.scss$/,
loader: 'style!css!sass?outputStyle=expanded&' +
'includePaths[]=' +
(encodeURIComponent(
path.resolve(process.cwd(), './node_modules')
)) +
'&includePaths[]=' +
(encodeURIComponent(
path.resolve( process.cwd(),
'./node_modules/grommet/node_modules'))
)
}

Using react-infinite-calendar with css-modules

I'd like to use react-infinite-calendar component for a personal project. It's not picking up the css. I think my webpack configuration is the problem as I'm using react-css-modules.
Could someone show me what I'd need to do to get it working?
My webpack configuration is:
const CopyWebpackPlugin = require('copy-webpack-plugin');
const path = require('path');
module.exports = {
entry: './index.js',
context: path.join(__dirname, 'client'),
devtool: 'source-map',
output: {
path: './dist/client/',
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
},
{
test: /\.json$/,
loader: 'json-loader'
},
{
// https://github.com/gajus/react-css-modules
test: /\.css$/,
loader: 'style!css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]'
}
]
},
resolve: {
extensions: ['', '.js', '.json']
},
plugins: [
new CopyWebpackPlugin([
{from: 'static/index.html'}
])
]
};
My date selector component is:
import React from 'react';
import InfiniteCalendar from 'react-infinite-calendar';
import 'react-infinite-calendar/styles.css'; // only needs to be imported once
import {TODAY} from '../../server/constants/date';
export default class DateSelector extends React.Component {
render() {
return (
<div>
<InfiniteCalendar
width={400}
height={600}
selectedDate={TODAY}
maxDate={TODAY}
/>
</div>
);
}
}
Another option is to exclude react-infinite-calendar from your CSS module loader and include it in the standard CSS loader.
That way you don't have to rename all of your CSS files.
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
},
{
test: /\.css$/,
exclude: /react-infinite-calendar/,
loader: 'style!css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]',
},
{
test: /\.css$/,
include: /react-infinite-calendar/,
loader: 'style-loader!css-loader',
},
]
I worked around this by having to separate webpack loaders for locally scoped css-modules and globally scoped ones. My webpack configuration is below and so for css modules I've had to name the files so they end with .module.css.
const CopyWebpackPlugin = require('copy-webpack-plugin');
const path = require('path');
module.exports = {
entry: './index.js',
context: path.join(__dirname, 'client'),
devtool: 'source-map',
output: {
path: './dist/client/',
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
},
{
test: /\.json$/,
loader: 'json-loader'
},
{
// https://github.com/gajus/react-css-modules
test: /\.module.css$/,
loader: 'style!css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]'
},
{
test: /^((?!\.module).)*css$/,
loader: 'style-loader!css-loader'
},
]
},
resolve: {
extensions: ['', '.js', '.json']
},
plugins: [
new CopyWebpackPlugin([
{from: 'static/index.html'}
])
]
};

Resources