Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot import CSS module in .tsx file

I am building basic react application with typescript but I am not able to import CSS file in index.tsx file

I am able to import index.css file following way:

import './index.css'; 
//this import gives typescript error when running webpack 

but not able to import as

import * as Styles from './index.css';

this is my webpack.config.js file

var path = require("path");
var HtmlWebpackPlugin = require('html-webpack-plugin')
var config = {
    mode:"none",
    entry:"./src/index.tsx",
    output:{
        path: path.resolve(__dirname,"dist"),
        filename: "bundle.js"
    },
    resolve:{
        extensions:[".ts", ".tsx", ".js"]
    },
    module:{
        rules:[
            {test:/\.tsx?$/, loader:"awesome-typescript-loader"},
            { test: /\.css$/, include: path.join(__dirname, 'src/'),
             loader:"typings-for-css-modules-loader" }
        ]
    },
    plugins:[new HtmlWebpackPlugin({
        template: './index.html'
    })]
};

module.exports = config;

I tried following links before posting but no luck

How to include .css file in .tsx typescript?

How to import css file for into Component .jsx file

https://github.com/parcel-bundler/parcel/issues/616

Thanks in advance

like image 412
AviatorX Avatar asked Dec 28 '18 17:12

AviatorX


People also ask

How do I import a CSS module?

To import a CSS Module into the corresponding component, import the css modules stylesheet as styles or [name]Styles : In JSX, use the defined CSS class as a className prop like so: From here, you can add as many other CSS modules you'd like, just remember to import each as a different name.

How do I import a CSS file into a TypeScript file?

First step — Importing css files in Typescript In order to do so your webpack configuration must have a loader for css files. I used css-loader for such. So you need to install it first with the command. Then you need to specify in you webpack configuration file in section module -> rules how CSS files will be loaded.


1 Answers

With the new version of React, to use CSS module you don't need to config anything in Webpack or reject your project. All your need to do is:

  1. Install css-modules-loader: https://github.com/gajus/react-css-modules
  2. Change the file name styles.css to styles.module.css
  3. Import the css file to your component:

    import styles from './styles.module.css'

  4. Use className in component:

    <div className={styles.app}> Hello World </div>

Demo project: https://codesandbox.io/s/kwyr5p378o

like image 102
Tony Bui Avatar answered Sep 28 '22 08:09

Tony Bui