How can I enable CSS Modules in React 16.13.1? - javascript

everyone! I'm trying to watch tutorials and read articles on how to enable CSS Modules in React 16.13.1. I understand that to do this, I must run "npm run eject", which I have done. Next, I know that I have to edit the "webpack.config.js" file. However, my webpack.config.js file looks very different than those online. A snippet of my webpack.config.js file is below, so what lines must I add and where to enable CSS Modules? If you need more info, please let me know.
test: cssRegex,
exclude: cssModuleRegex,
use: getStyleLoaders({
importLoaders: 1,
sourceMap: isEnvProduction && shouldUseSourceMap,
}),

Name your file styles.module.css works in CRA

Example you create a css file in the same folder as the js file:
MyComponent.module.css
.Mycomponent {
padding: 10px;
margin: 5px;
}
MyComponent.js
import React from 'react';
import classes from "./MyComponent.module.css";
const MyComponent = () => {
return (
<div className={classes.Mycomponent}>
This div needs some padding and margin
</div>
)
}
export default MyComponent

Related

Unable to import css files into NextJs project

Currently I have my index.js file that has my display components. For CSS I have downloaded a css file from an external source. I am then adding the .css file into my styles folder that comes when you make the initial npx create-next-app. This file I'm then trying to import into my index.js file like so: import bootStyles from "../styles/bootstrap.css". But doing this gives me this error:
error - ./styles/bootstrap.css Global CSS cannot be imported from
files other than your Custom . Please move all global CSS imports
to pages_app.js. Or convert the import to Component-Level CSS (CSS
Modules). Read more: https://nextjs.org/docs/messages/css-global
Location: pages\index.js
Additionally I have also tried using the Head component like so:
import Head from 'next/head'
<Head>
<title>Create Next App</title>
<link rel="stylesheet" href="../styles/bootstrap.css"/>
</Head>
This doesnt show an error but the styles still dont reflect on my webpage.
Either put all your CSS imports in _app.tsx or you can add *.module.css to your filenames so they get picked up.
You can also override the nextjs webpack config:
// next.config.js
module.exports = {
webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
return config
},
}
...
{
test: /\.s?[ac]ss$/,
use: ['style-loader', 'css-loader', 'sass-loader'],
exclude: [/node_modules/],
},
In order to override the module rules and css loader, however I wouldn't recommend this if you don't know what you're doing.

CSS Module gets bundled but is not referenced using TSDX which uses Rollup underhood

I have created a React library using TSDX → https://github.com/deadcoder0904/react-typical
It uses CSS Modules & attaches styles to the React library.
The bundle correctly outputs CSS file into the dist/ folder but it never really references it as it should.
This causes my styles to not show up at all.
Here's my complete tsdx.config.js:
const postcss = require('rollup-plugin-postcss');
const { terser } = require('rollup-plugin-terser');
const autoprefixer = require('autoprefixer');
const cssnano = require('cssnano');
module.exports = {
rollup(config, options) {
config.plugins.push(
postcss({
modules: true,
plugins: [
autoprefixer(),
cssnano({
preset: 'default',
}),
],
inject: false,
// only write out CSS for the first bundle (avoids pointless extra files):
extract: !!options.writeMeta,
minimize: true,
}),
terser()
);
return config;
},
};
If you see the dist/ folder at https://yarnpkg.com/package/#deadcoder0904/react-typical?files, then you'll notice it has index.js file but it doesn't reference the .css file at all.
Same thing with every .js file in dist/ folder. No file references .css file & the CSS code isn't bundled at all so it just doesn't use styles.
How do I solve this?
From my understanding, normally a library usually introduce the component & styles separately and let the users know in the document if they want to use default style then let import css file too such as:
import ReactTypical from "react-typical"
import "react-typical/dist/react-typical.cjs.development.css"
That is as same as your case I guess
Or you would set your style by default without asking them to import manually which means you have to refine your config by setting inject: true, it will import your css context into your js file then execute at runtime to append the script in the <head /> of the document. Then your changing config would look like:
postcss({
modules: true,
plugins: [
autoprefixer(),
cssnano({
preset: 'default',
}),
],
// Append to <head /> as code running
inject: true,
// Keep it as false since we don't extract to css file anymore
extract: false,
})
In order to work with storybook, add following css rules to your webpack storybook config ./story/main.js:
// Remove the existing css rule
config.module.rules = config.module.rules.filter(
f => f.test.toString() !== '/\\.css$/'
);
config.module.rules.push(
{
test: /\.css$/,
use: [
'style-loader',
'css-loader',
],
include: path.resolve(__dirname, "../src"),
}
)
But you miss them in your package dependency, just remember to add them:
npm i -D style-loader css-loader

CSS into JS using webpack

I`m trying to paste a CSS Code into a JS File using webpack
My flux is the following
SASS file > CSS content > PostCSS > css file
{
test: /\.(sass|scss)$/,
exclude: /node_modules/,
use: [
MiniCSSExtractPlugin.loader,
'css-loader',
'postcss-loader',
{
loader: 'sass-loader',
options: {
sourceMap: true,
sassOptions: {
outputStyle: 'compressed'
}
}
}
]
}
But the MiniCSSExtractPlugin gets me the content into a css file.
I'm use Lit Element so the styles should be declare with css function part of lit-element on the following way
import {css} from 'lit-element';
export default css`
:host {
display: inline;
}
`;
Is there any way to generate css code as a string and paste it into js file?
To import a CSS file into JS (w/webpack) you need to configure webpack with the following loaders:
css-loader
style-loader
Both available with NPM:
$ npm i css-loader style-loader --save-dev
And add this entry to the module.rules array in your webpack configuration:
{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
]
}
The result
Both of this loaders correctly configured will allow you to do the following sentence in JavaScript:
import myStyles from './your-css-file.css';
And then, you can just paste them into literal templates as follows:
static get styles() {
return css`${myStyles}`;
}
Additionally:
With a deep knowledge into what you might be talking about, you might need to take a look around #cells/cells-cli files and add those loaders into webpack configuration. Otherwise, you may need to create a webpack.config.js file in every lit-element component, which might not be the best for the current architecture.
Nice to see you around here, ¡saludos!;)
#k3llydev, I tried your suggestion and couldn't get it to work. Do you have any suggestions, specifically when you say "both of these loaders correctly configured will allow you to do the following"? I'd like to be able to import the CSS and then use it directly in the styles getter like you show in your example, but I had to do this as a workaround:
import MyImportedStyle from './some.css';
static get styles () {
return [
css`${unsafeCSS(MyImportedStyle.toString())}`
];
}
While using the 'to-string-loader' in webpack:
{
test: /\.css$/i,
use: ['to-string-loader', 'css-loader'],
}
This worked out for me and did what I wanted, but if I could avoid using the to-string-loader and could use the imported object directly, that would be idea. Any suggestions?
This way should do what the original poster asked for, a way to get the CSS as a string and use it in your LitElement.

How to bundle vendor CSS files into a React app with Webpack?

I have some 3rd party libs, like Mapbox GL, which are installed via npm and have some CSS files they rely on in their work.
As for Mapbox GL, there is mapbox-gl/dist/mapbox-gl.css in node_modules. I have index.html which is used as the entry point for my React app and contains a link to a CSS file with some defaults.
<link rel="stylesheet" href="/vendor/core.css">
All other CSS rules are provided by CSS modules, so I have a single CSS file in a React UI component folder and import it from the component like this:
import * as style from './MyComponent.css';
How do I import vendor CSS files, like Mapbox GL example above and make the rules from it apply to the app?
If your vendor css files are specific to a component, you can import them directly into your component, like this:
// Component1.js
import React from 'react';
...
import 'vendor/path/to/styles.css';
...
If you want to import a general css file (such as normalize.css), you can import them into your top-level html view. I usually have a JSX file which is transpiled by webpack to index.html. So you can do this:
// index.jsx (transpiled to index.html)
<style
dangerouslySetInnerHTML={{
__html: require('!css-loader!normalize.css/normalize.css'),
}}
/>
Or, if you have pure HTML, you can let webpack do it for you using the html-loader
For your reference, this is my webpack.config:
webpackConfig = {
module: {
rules = [
{
// excluding for node-modules
test: /.css$/,
exclude: path.resolve('./node_modules'),
use: [
'style-loader',
{
loader: 'css-loader',
options: {
modules: true,
camelCase: true,
importLoaders: 1,
localIdentName: '[path][name]__[local]--[hash:base64:5]',
},
},
'postcss-custom-loader',
],
},
{
// only for node-modules
test: /.css$/,
include: path.resolve('./node_modules'),
use: ['style-loader', 'css-loader', 'postcss-custom-loader'],
},
...
}

How to import a CSS file in a React Component

I want to import a CSS file into a react component.
I've tried import disabledLink from "../../../public/styles/disabledLink"; but I get the error below;
Module not found: Error: Cannot resolve 'file' or 'directory' ../../../public/styles/disabledLink in c:\Users\User\Documents\pizza-app\client\src\components # ./client/src/components/ShoppingCartLink.js 19:20-66 Hash: 2d281bb98fe0a961f7c4 Version: webpack 1.13.2
C:\Users\User\Documents\pizza-app\client\public\styles\disabledLink.css is the location of the CSS file I'm trying to load.
To me it seems like import is not looking up the correct path.
I thought with ../../../ it would start to look up the path three folder layers above.
C:\Users\User\Documents\pizza-app\client\src\components\ShoppingCartLink.js is the location of the file that should import the CSS file.
What am I doing wrong and how can I fix it?
You don't even have to name it if you don't need to:
e.g.
import React from 'react';
import './App.css';
see a complete example here (Build a JSX Live Compiler as a React Component).
You need to use css-loader when creating bundle with webpack.
Install it:
npm install css-loader --save-dev
And add it to loaders in your webpack configs:
module.exports = {
module: {
loaders: [
{ test: /\.css$/, loader: "style-loader!css-loader" },
// ...
]
}
};
After this, you will be able to include css files in js.
I would suggest using CSS Modules:
React
import React from 'react';
import styles from './table.css';
export default class Table extends React.Component {
render () {
return <div className={styles.table}>
<div className={styles.row}>
<div className={styles.cell}>A0</div>
<div className={styles.cell}>B0</div>
</div>
</div>;
}
}
Rendering the Component:
<div class="table__table___32osj">
<div class="table__row___2w27N">
<div class="table__cell___2w27N">A0</div>
<div class="table__cell___1oVw5">B0</div>
</div>
</div>
The following imports an external CSS file in a React component and outputs the CSS rules in the <head /> of the website.
Install Style Loader and CSS Loader:
npm install --save-dev style-loader
npm install --save-dev css-loader
In webpack.config.js:
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: [ 'style-loader', 'css-loader' ]
}
]
}
}
In a component file:
import './path/to/file.css';
CSS Modules let you use the same CSS class name in different files without worrying about naming clashes.
Button.module.css
.error {
background-color: red;
}
another-stylesheet.css
.error {
color: red;
}
Button.js
import React, { Component } from 'react';
import styles from './Button.module.css'; // Import css modules stylesheet as styles
import './another-stylesheet.css'; // Import regular stylesheet
class Button extends Component {
render() {
// reference as a js object
return <button className={styles.error}>Error Button</button>;
}
}
The solutions above are completely changed and deprecated. If you want to use CSS modules (assuming you imported css-loaders) and I have been trying to find an answer for this for such a long time and finally did. The default webpack loader is quite different in the new version.
In your webpack, you need to find a part starting with cssRegex and replace it with this;
{
test: cssRegex,
exclude: cssModuleRegex,
use: getStyleLoaders({
importLoaders: 1,
modules: true,
localIdentName: '[name]__[local]__[hash:base64:5]'
}),
}
You can import css file if css file reside in a same folder where you want to import than just simple try this
import './styles.css'
if css file is far away from our component that navigate that place where file is reside and use this like
import '../mainstyles/styles.css'
In cases where you just want to inject some styles from a stylesheet into a component without bundling in the whole stylesheet I recommend https://github.com/glortho/styled-import. For example:
const btnStyle = styledImport.react('../App.css', '.button')
// btnStyle is now { color: 'blue' } or whatever other rules you have in `.button`.
NOTE: I am the author of this lib, and I built it for cases where mass imports of styles and CSS modules are not the best or most viable solution.
You can also use the required module.
require('./componentName.css');
const React = require('react');
Install Style Loader and CSS Loader:
npm install --save-dev style-loader
npm install --save-dev css-loader
Configure webpack
module: {
loaders: [
{
test: /\.css$/,
loader: 'style-loader'
}, {
test: /\.css$/,
loader: 'css-loader',
query: {
modules: true,
localIdentName: '[name]__[local]___[hash:base64:5]'
}
}
]
}
Using extract-css-chunks-webpack-plugin and css-loader loader work for me, see below:
webpack.config.js Import extract-css-chunks-webpack-plugin
const ExtractCssChunks = require('extract-css-chunks-webpack-plugin');
webpack.config.js Add the css rule,
Extract css Chunks first then the css loader css-loader will embed them into
the html document, ensure css-loader and extract-css-chunks-webpack-plugin are in the package.json dev dependencies
rules: [
{
test: /\.css$/,
use: [
{
loader: ExtractCssChunks.loader,
},
'css-loader',
],
}
]
webpack.config.js Make instance of the plugin
plugins: [
new ExtractCssChunks({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: '[name].css',
chunkFilename: '[id].css'
})
]
And now importing css is possible
And now in a tsx file like index.tsx i can use import like this
import './Tree.css' where Tree.css contains css rules like
body {
background: red;
}
My app is using typescript and this works for me, check my repo for the source :
https://github.com/nickjohngray/staticbackeditor
You can import your .css file in .jsx file
Here is an example -
import Content from '../content/content.jsx';

Categories

Resources