How to setup babel-plugin-react-css-modules in create-react-app? - reactjs

I really like the separation of className and styleName that babel-plugin-react-css-modules offers for global and local styles respectively, but have had some trouble getting the plugin to work with create-react-app.
I've tried installing the plugin by running
npm install babel-plugin-react-css-modules --save
... as it says to do in the project (github https://github.com/gajus/babel-plugin-react-css-modules#css-modules) ...
... and have also used craco as suggested in a similar thread (#5113) to help overcome the limitations of create-react-app without the need to eject, but am still unable to import a scss file and reference to it using styleName.
Does anyone know if I'm missing something else here? Sorry if it's a noob question, I'm new to React and have been looking for a solution to this for a while now.

1. add the plugin to .babelrc first.
"plugins": [
["babel-plugin-react-css-modules",
{
"webpackHotModuleReloading": true,
"autoResolveMultipleImports": true
}],....
]
2. add css rule in webpack.config.js.
below is my configuration that you can reference from.
make sure that
2.1 option modules set to true.
2.2 localIdentName follow this format. localIdentName: "[path]___[name]__[local]___[hash:base64:5]"
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /(node_modules|bower_components)/,
use: [
{
loader: "babel-loader",
options: { cacheDirectory: true }
}
]
},
{
test: /\.css$/i,
use: [
{
loader: ExtractCssChunks.loader,
options: { hot: true }
},
{
loader: "css-loader", //generating unique classname
options: {
importLoaders: 1, // if specifying more loaders
modules: true,
sourceMap: false,
localIdentName: "[path]___[name]__[local]___[hash:base64:5]" //babel-plugin-css-module format
//localIdentName: "[path][name]__[local]" //recommended settings by cssloader#local-scope , this option generate unique classname for compiled css
}
}
]
},

Related

Unable to skip 3rd party library CSS from CSS-Module transformation

I am trying CSS Modules for the first time with React and Webpack and I came across at least three ways to achieve it:
css-loader
react-css-modules
babel-plugin-react-css-modules
I went with babel-plugin-react-css-modules in order to balance code simplicity and performance and everything seems to be working fine except for one thing: my 3rd party libraries (Bootstrap and Font Awesome) are also included in CSS Modules transformation.
<NavLink to="/about" styleName="navigation-button"></NavLink>
The above assigns a properly transformed className to the NavLink. However, a span inside needs to refer to global styles in order to render an icon.
<span className="fa fa-info" />
The above span is not assigned a transformed className which is expected, but my bundled stylesheet does not have these CSS classes as they are being transformed into something else, to simulate local scope.
Below is the content in my .babelrc file to activate babel-plugin-react-css-modules:
{
"presets": ["env", "react"],
"plugins": [
["react-css-modules", {
"generateScopedName": "[name]__[local]___[hash:base64:5]",
"filetypes": {
".less": {
"syntax": "postcss-less"
}
}
}]
]
}
In my Webpack configuration, below is the section to configure css-loader for transforms:
{
test: /\.(less|css)$/,
exclude: /node_modules/,
use: extractCSS.extract({
fallback: 'style-loader',
use: [
{
loader: 'css-loader',
options: {
minimize: true,
modules: true,
sourceMap: true,
localIdentName: '[name]__[local]___[hash:base64:5]'
}
},
{
loader: 'less-loader'
}
]
})
}
As far as I have read, the above rule should exclude the library stylesheets and I also tried adding another rule specifically for the excluded stylesheets, however that did not seem to work, as I guess as those stylesheets were still transformed with the original rule.
In order to import CSS from the two libraries, I have the below two lines in my parent stylesheet that declares some global styles:
#import '../../../node_modules/bootstrap/dist/css/bootstrap.min.css';
#import '../../../node_modules/font-awesome/css/font-awesome.min.css';
I find these two approaches below might be helpful:
https://stackoverflow.com/a/52294675
https://github.com/css-modules/css-modules/pull/65#issuecomment-412050034
In short, there seems to be no options to ignore/exclude certain paths from being modularized by the css-modules webpack plugin so far. Ideally it should be supported by the plugin, but here're some approaches you can try out:
use two webpack rules to utilise the webpack rule exclusion/inclusion:
module.exports = {
rules: [
{
test: /\.css$/,
exclude: /node_modules/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
modules: true,
localIdentName: '[path]__[local]___[hash:base64:5]',
},
},
],
},
{
test: /\.css$/,
include: /node_modules/,
use: ['style-loader', 'css-loader']
}
]
}
...or, inject into webpack's getLocalIdent from the second answer above to manually exclude certain paths.
const getLocalIdent = require('css-loader/lib/getLocalIdent');
{
loader: 'css-loader',
options: {
modules: true,
localIdentName: '[path][name]__[local]--[hash:base64:5]',
getLocalIdent: (loaderContext, localIdentName, localName, options) => {
return loaderContext.resourcePath.includes('semantic-ui-css') ?
localName :
getLocalIdent(loaderContext, localIdentName, localName, options);
}
}
}
For me using :global worked :
.my-component {
:global {
.external-ui-component {
padding: 16px;
// Some other styling adjustments here
}
...
}
}
Ps: for doing it with webpack config, please see another answer.
source
Updated solution from playing771
{
loader: 'css-loader',
options: {
modules: {
auto: (resourcePath) => !resourcePath.includes('node_modules'),
localIdentName: '[name]__[local]__[hash:base64:5]',
},
},
},

Webpack AngularJS Sourcemaps issue

I've been struggling with getting my source-maps working in my app for quite a while. I have set
devtool: 'source-map',
in the webpack configuration, but they are still not available in the Chrome devtools.
I pushed a really simple app using my FE Stack hoping someone could identify the issue, whether it is with webpack, angular, or some other library. https://github.com/coreysnyder/Angular-Webpack3-Seed
Here are the versions I'm running:
{
CoreyApp: '1.0.0',
npm: '4.4.4',
ares: '1.10.1-DEV',
http_parser: '2.7.0',
icu: '57.1',
modules: '48',
node: '6.9.0',
openssl: '1.0.2j',
uv: '1.9.1',
v8: '5.1.281.84',
zlib: '1.2.8'
}
OSX 10.12.6
You will probably have to setup source map for different loaders individually.
For 'ng-annotate-loader' (Docs)
use: [{
loader: 'ng-annotate-loader',
options: {
add: true,
single_quotes: true ,
map: { inline: true, inFile: 'app.js', sourceRoot: __dirname + '/app' }}
}]
For less you can use documentation option like #ahmedelgabri suggested
use: [{
loader: "style-loader"
}, {
loader: "css-loader", options: {
sourceMap: true
}
}, {
loader: "less-loader", options: {
sourceMap: true
}
}]
Old post before OP github changes.
Other option is to add devtoolLineToLine: true in your output, if you want to use devtool: 'source-map'. But devtoolLineToLine is deprecated, so consider changing devtool to something else. devtool: 'source-map' demo image
output: isTest ? {} : {
devtoolLineToLine: true, // <= this line
sourceMapFilename: '[name].map',
path: __dirname + '/dist',
filename: '[name].bundle.js',
publicPath: publicPath
},
Alternatively you could use devtool: 'eval' or some variation of eval, like cheap-module-eval-source-map (similar behavior, but without file names) also works fine for me
I could fix your source maps for JS files, by adding the babel-loader. To do this, you need to install babel-loader:
npm i -D babel-loader#8.0.0-beta.0 #babel/core #babel/preset-env
and then extend your rule for .js
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: [
{
loader: 'ng-annotate-loader',
options: { add: true, single_quotes: true }
},
{
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env']
}
}
]
}, [...]
]
Ready further details on babel-loader github repo
There is nothing wrong with the Webpack config here https://github.com/coreysnyder/Angular-Webpack3-Seed
here is a gif using your code & setting a breakpoint in view1 file
And here is why the text is blue
And I can see the source just fine
The main issue is the less-loader you need to pass the source-maps options for both, the less-loader & css-loader check the readme
{
test: /\.less$/,
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
options: {
sourceMap: true,
},
},
{
loader: 'less-loader',
options: {
sourceMap: true,
},
},
],
},
After doing this you will be able to debug from the styles panel like this
If you want to edit directly the .less files the readme mentions a blog post that can help with this https://github.com/webpack-contrib/less-loader#source-maps
I hope this answers your question

How to setup react app with SCSS? (Errors)

I am trying to setup my react project so I can use SASS in the SCSS format.
This is in my webpack.config.dev.js:
{
test: /\.scss$/,
exclude: /node_modules/,
use: [
require.resolve('style-loader'),
{
loader: require.resolve('css-loader'),
options: {
importLoaders: 1,
},
},
{
loader: require.resolve('sass-loader'),
}
]
}
I import the scss files into my jsx in two different ways:
import './index.scss';
import css from './ModalWrapper.scss';
When I run the app I am currently getting the error:
./src/index.scss
Module build failed:
body {
^
Invalid CSS after "m": expected 1 selector or at-rule, was "module.exports = __"
in /pathtoapp/web/src/index.scss (line 1, column 1)
It appears me, that one, react is trying to interpret the SCSS as CSS which should work. In addition, react believes that body is not valid CSS. There, I would believe that neither CSS or SCSS are being loaded correctly.
Any help would be appreciated. There are quite a few unanswered questions to this problem.
If you are on Webpack 3, add this to module.rules
{
test: /\.scss$/,
loader: [
require.resolve('style-loader'),
require.resolve('css-loader'),
require.resolve('sass-loader'),
]
},
And then add the file loader and make sure to add .scss to the array of the key exclude like this
{
loader: require.resolve('file-loader'),
// Exclude `js` files to keep "css" loader working as it injects
// it's runtime that would otherwise processed through "file" loader.
// Also exclude `html` and `json` extensions so they get processed
// by webpacks internal loaders.
exclude: [/\.js$/, /\.html$/, /\.json$/, /\.scss$/,],
options: {
name: 'static/media/[name].[hash:8].[ext]',
},
}
And of course, make sure you have style-loader, sass-loader, css-loader and file-loader in you package.json. This code snippet worked for me when using the latest version of create-react-app.
This is what ended up working for me:
{
test: /\.scss$/,
use: [{
loader: 'style-loader'
}, {
loader: 'css-loader',
options: {
modules: true,
sourceMap: true,
localIdentName: "[local]___[hash:base64:5]",
},
}, {
loader: 'sass-loader',
options: {
outputStyle: "expanded",
sourceMap: true,
},
}]
},
I'm sure the other answers are just as good, but for maximum brevity, this works for me (I erased some of the internal webpack.config.dev.js comments presumably made by the create react folks):
module: {
strictExportPresence: true,
rules: [
{
test: /\.scss/,
use: ['style-loader','css-loader', 'sass-loader']
},...
I don't know if it matters, but I put this on the top. Also, yes, make sure to add the scss file to the excluded array as mentioned above.

Webpack 2 CSS Modules support

Right now I'm moving my current project from Webpack 1 to Webpack 2 and I encounter some problems with css modules which previously worked fine. In particular, I use css-loader and react-css-modules. My current development configuration is the following:
test: /module\.css$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
modules: true,
importLoaders: 1,
localIdentName: '[name]__[local]___[hash:base64:5]'
}
},
'postcss-loader'
]
It works fine. For production I use ExtractTextPlugin (version 2.0.0-beta.4) and my Webpack config for that case goes like this:
test: /module\.css$/,
loader: ExtractTextPlugin.extract({
fallbackLoader: 'style-loader',
loader: [
{
loader: 'css-loader',
options: {
modules: true,
importLoaders: 1,
localIdentName: '[hash:base64:5]'
}
},
'postcss-loader'
]
}),
In this case build fails with the following error:
Module build failed: Error: composition is only allowed
when selector is single :local class name
So it seems like it doesn't prepend local prefixes. It is also mentioned in the css-loader documentation:
Note: For prerendering with extract-text-webpack-plugin you should
use css-loader/locals instead of style-loader!css-loader in the
prerendering bundle. It doesn't embed CSS but only exports the
identifier mappings.
So I tried loader: 'css-loader/locals' as well as adding it to options, but, unfortunately, nothing works.
I also tried to fix this problem with postcss postcss-modules plugin. It fixes the build, but when I try to start my application it looks like it doesn't have appropriate imports of css name mappings.
In case, that somebody will face the same problem in the future. For this version of ExtractTextPlugin (2.0.0-beta.4) you should set loader parameters in Webpack-1 way. Concretely:
loader: ExtractTextPlugin.extract({
fallbackLoader: 'style-loader',
loader: [
'css-loader?modules&importLoaders=1&localIdentName=[hash:base64:5]',
'postcss-loader'
]
}),
Works fine for me

How do I configure Webpack to support ES7 Decorators [duplicate]

I've got a project written in ES6 with webpack as my bundler. Most of the transpiling works fine, but when I try to include decorators anywhere, I get this error:
Decorators are not supported yet in 6.x pending proposal update.
I've looked over the babel issue tracker, and haven't been able to find anything on it there, so I'm assuming I'm using it wrong. My webpack config (the relevant bits):
loaders: [
{
loader: 'babel',
exclude: /node_modules/,
include: path.join(__dirname, 'src'),
test: /\.jsx?$/,
query: {
plugins: ['transform-runtime'],
presets: ['es2015', 'stage-0', 'react']
}
}
]
I have no trouble with anything else, arrow functions, destructuring all work fine, this is the only thing that doesn't work.
I know I could always downgrade to babel 5.8 where I had it working a while ago, but if there's any way to get this working in the current version (v6.2.0), it would help.
This Babel plugin worked for me:
https://github.com/loganfsmyth/babel-plugin-transform-decorators-legacy
npm i --save-dev babel-plugin-transform-decorators-legacy
.babelrc
{
"presets": ["es2015", "stage-0", "react"],
"plugins": [
["transform-decorators-legacy"],
// ...
]
}
or
Webpack
{
test: /\.jsx?$/,
loader: 'babel',
query: {
cacheDirectory: true,
plugins: ['transform-decorators-legacy' ],
presets: ['es2015', 'stage-0', 'react']
}
}
React Native
With react-native you must use the babel-preset-react-native-stage-0 plugin instead.
npm i --save babel-preset-react-native-stage-0
.babelrc
{
"presets": ["react-native-stage-0/decorator-support"]
}
Please see this question and answer for a complete explanation.
After spending 5 minutes on the babeljs slack webchat, I found out that decorators are broken in the current version of babel (v6.2). The only solution seems to be to downgrade to 5.8 at this time.
It would also seem they moved their issue tracker from github to https://phabricator.babeljs.io
I write all this down, since after hours of searching I have found the current documentation very poor and lacking.
Installing only babel-plugin-transform-decorators-legacy didn't work for me (I have a configuration using enzyme along with karma). Turns out installing transform-class-properties: transform-class-properties and also making sure that the legacy plugin is before the transform class plugin as per the docs in transform-decorators-legacy finally made it work for me.
I'm also not using a .babelrc file, but adding this to my karma.conf.js file worked for me:
babelPreprocessor: {
options: {
presets: ['airbnb', 'es2015', 'stage-0', 'react'],
plugins: ["transform-decorators-legacy", "transform-class-properties"]
}
}
I also added it to my loaders:
loaders: [
{
test: /\.js$/,
loader: 'babel',
exclude: path.resolve(__dirname, 'node_modules'),
query: {
presets: ['airbnb', 'es2015', 'stage-0', 'react'],
plugins: ["transform-decorators-legacy", "transform-class-properties"]
}
},
You just need a transform decorators plugin: http://babeljs.io/docs/plugins/transform-decorators/
If you upgraded your project from Babel 6 to Babel 7, then you want to install #babel/plugin-proposal-decorators.
If you want to support legacy decorators as used in Babel 5, you need to configure your .babelrc as follows:
plugins: [
['#babel/plugin-proposal-decorators', { legacy: true }],
['#babel/plugin-proposal-class-properties', { loose: true }],
]
Ensure #babel/plugin-proposal-decorators comes before #babel/plugin-proposal-class-properties in the case that you are making use of the latter.

Resources