score:-10
let styles = require("./styles.css");
is the best approch because it is es5 version of javascript which is compatible with every feature of react.import * as styles from './styles.css'
is es6 version of javascript.
score:2
I think now typescript can import css file by simply doing import 'fileTobeImportedPath.css'
score:2
This case is related to Typescript. You can add typings.d.ts
in your project with this content:
declare module "*.module.css";
declare module "*.module.scss";
It is good practice to use file name with *.module.*
format if you want to enable CSS Module.
css-loader
will enable CSS Module automatically for files with name that satisfy this RegEx: /\.module\.\w+$/i
. This feature is customable by setting options.modules
property as an object.
For example:
import style from './App.module.css'; // CSS Module enabled
import './index.css'; // Plain CSS loaded
For recent configuration, you can add this rule to webpack.config.js
:
{
test: /\.css$/,
use: [
'style-loader',
{
loader: "css-loader",
options: {
modules: {
localIdentName: "[hash:base64]", // default
auto: true // default
},
sourceMap: true
}
},
]
},
A custom configuration example:
{
loader: "css-loader",
options: {
modules: {
localIdentName: "[name]_[local]_[hash:base64]", // custom class name format
auto: /\.cmod\.\w+$/i, // custom auto enable CSS Module for "*.cmod.css" format
},
}
},
Complete documentation is HERE.
score:3
Or import using require webpack function
This is just what I used to do and still have that code in a few of my projects out there.
Now : I wrote typestyle : http://typestyle.github.io/#/ but you don't have to use it. Just stick with const styles = require('./styles.css')
if it makes you happy. FWIW you can also use raw css with typestyle if you want http://typestyle.github.io/#/raw
score:6
In 2022, all I needed to do it to add Globals.d.ts
file under the src
folder
with
declare module "*.module.css";
declare module "*.module.scss";
Then I can import CSS modules in my typescript files as usual for css or scss files:
import styles from "./Team.module.scss";
score:34
I have added a file named Global.d.ts
or typings.d.ts
to my ./src
folder with some type definitions:
declare module "*.module.css";
Webpack css config:
{
test: /\.css$/,
use: [
isProductionBuild ? MiniCssExtractPlugin.loader : "style-loader",
{
loader: "css-loader",
options: {
modules: true,
importLoaders: 1,
localIdentName: "[name]_[local]_[hash:base64]",
sourceMap: true,
minimize: true
}
}
]
},
Then I simply import the module like: import styles from "./App.module.css";
score:53
A) As you are saying, there is one simplest (not best) option to use require:
const css = require('./component.css')
- We need to have typings for
require
as it's not standard feature in typescript. Simplest typing for this specific require may be:
declare function require(name: string): string;
Webpack will then compile typescript and use modules properly - BUT without any IDE help and class names checks for build.
B) There is better solution to use standard import:
import * as css from './component.css'
- enables full class names IntelliSense
- requires types definition for each css file, otherwise
tsc
compiler will fail
For proper IntelliSense, Webpack needs to generate types definition for each css file:
Use webpack typings-for-css-modules-loader
webpackConfig.module.loaders: [ { test: /\.css$/, loader: 'typings-for-css-modules?modules' } { test: /\.scss$/, loader: 'typings-for-css-modules?modules&sass' } ];
Loader will generate
*.css.d.ts
files for each of css files in your codebase- Typescript compiler will understand that css import will be module with properties (class names) of type string.
Mentioned typings-for-css-loader
contains a bug and because of types file generation delay, it's best to declare global *.css
type in case our *.css.d.ts
file is not generated yet.
That little bug scenario:
- Create css file
component.css
- Include it in component
import * as css from './component.css'
- Run
webpack
- Typescript compiler will try to compile code (ERROR)
- Loader will generate Css modules typings file (
component.css.d.ts
), but it's late for typescript compiler to find new typings file - Run
webpack
again will fix build error.
Easy fix is to create global definition (eg. file called typings.d.ts
in your source root) for importing CSS Modules:
declare module '*.css' {
interface IClassNames {
[className: string]: string
}
const classNames: IClassNames;
export = classNames;
}
This definition will be used if there is no css file generated (eg. you have added new css file). Otherwise will be used generated specific (needs to be in same folder and named same as source file + .d.ts
extension), eg. component.css.d.ts
definition and IntelliSense will work perfectly.
Example of component.css.d.ts
:
export const wrapper: string;
export const button: string;
export const link: string;
And if you don't want to see generated css typings you may setup filter in IDE to hide all files with extension .css.d.ts in your sources.
score:53
Now in the year 2021, all you need to do is add a src/Globals.d.ts
to your project with these lines:
declare module "*.module.css";
declare module "*.module.scss";
// and so on for whatever flavor of css you're using
Then install and add
{
"compilerOptions": {
"plugins": [{ "name": "typescript-plugin-css-modules" }]
}
}
to your tsconfig.
Example of this correctly functioning in VS code after making that simple change (root is a class defined in my stylesheet):
Webpack and tsc also compile correctly on the command line.
Source: stackoverflow.com
Related Query
- How to import CSS modules with Typescript, React and Webpack
- Use CSS Modules in React components with Typescript built by webpack
- How can I build a React app with Webpack and import an assets folder?
- How to determine the order of css in my create react app build with webpack and customize-cra?
- Error using css modules in typescript react with webpack config
- How can you use CSS modules together with Typescript, React and Webpack?
- How to override css and import with another component in react js
- Configuring CSS modules in development/production with webpack and React
- How to use CSS Modules with webpack in React isomorphic app?
- import react css from modules not working with Classname and mapping
- How to import npm module css as global with webpack and typescript?
- How to apply global styles with CSS modules in a react app?
- How to define css variables in style attribute in React and typescript
- How to set up Babel 6 stage 0 with React and Webpack
- Multiple classNames with CSS Modules and React
- Remove unused css with React and Webpack
- How to use React with Typescript and SASS
- How to style child components in React with CSS Modules
- How to use vw and vh css with React Native
- How to import scss file as variable in react with typescript
- How to import js modules (with absolute path) in my typescript file in React application?
- how to make webpack typescript react webpack-dev-server configuration for auto building and reloading page
- React and typescript with webpack typing issue
- How to enable absolute path aliases with eslint import plugin in a typescript react project?
- How do you correctly use React.lazy() in Typescript to import a react component with a generic type parameter?
- CSS Code Splitting with Webpack 2 and React Router
- Test with Mocha and Enzyme a React component that uses React CSS Modules
- How to import from React-Select CDN with React and Babel?
- Typescript and React (with Gatsby loader): unable to import images as modules
- How to use Jest with React and Webpack
More Query from same tag
- Confused about return value in arrow function?
- backend code not working to push id to friends property array
- After map function on populated array items appear to be null
- On Opening one dropdown the other drop down if it is opened should close
- Show icon across two rows in a mui table
- Not working handleChange when copy & paste in React
- How to render jsx calling non component function in React?
- Zoom in and out on image in React.js
- trying to download a file from an azure file share via react app
- How to open specific post dropdown menu without effecting the others?
- Fix React Hook useEffect has a missing dependency
- ReactJS Invalid hook call while add useStyle variable
- Position content in ExpansionPanelSummary [React Material-UI]
- How to work with combineReducer in ReactRedux? And combineReducers's 'sate' object to the multiple reduces
- NEXT JS req.body undefined
- can I get onChange length each input value using useForm in React
- How do I display data fetched from firestore to a boostrap table in reactjs? I'm able to fetch but cannot display with the standard way of doing it
- Mouse hover on textfield doesn't work after typing
- Way for child to inherit all properties from parent
- Dynamic defaultValue on Combobox React Widgets
- The transition set in React with classnames does'n work
- Change color of <td> independetly in react js
- Inline map statement React
- Having trouble putting a <Tab> in a reusable function
- can you pass a component through props to children
- React.memo and shallow comparision
- why value is not set on dropdown in react js (allready set value props)?
- Submitting radio inputs with ReactJs and setting active class to the current selection
- start with the default state upon rendering the component for the first time ! where no mood has been selected yet
- Highlight current date in react Gantt timeline