Unable to bring in CSS module in a .tsx file

I am currently working on a basic React application with TypeScript, but I am encountering difficulty when trying to import a CSS file into my index.tsx file.

I have successfully imported the index.css file using this method:

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

However, I am facing issues when trying to import it as:

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

Below is an excerpt from 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;

Despite searching through various resources such as forums and links without any success:

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

I appreciate your help in advance.

Answer №1

If you're using the latest version of React, incorporating CSS modules is now easier than ever. There's no need to mess around with Webpack configurations or overhaul your entire project setup. All you have to do is:

  1. Firstly, make sure to install css-modules-loader: https://github.com/gajus/react-css-modules
  2. Rename your CSS file from styles.css to styles.module.css
  3. Import the css module into your component:

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

  4. Now, you can simply use className within your component:

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

To see a demo project in action, visit: https://codesandbox.io/s/kwyr5p378o

Answer №2

According to the documentation for typings-for-css-modules-loader, it is recommended to import your css in one of the following ways:

Option 1:

import styles from './index.css';

Option 2:

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

Your code example is missing the keyword from.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips on utilizing Twitter Boootstrap's form validation tooltip messages

Before anything else, let me clarify that I am not inquiring about creating tooltips from scratch using Bootstrap's javascript guide, which can be found in the documentation. I recently utilized type="email" with version v3.3.1. It automatically vali ...

Troubleshooting SCSS Issues in NextJS

Can anyone help me with debugging SCSS in NEXT.JS? I've been trying to figure it out but haven't had any luck. When I use @debug on a SCSS module, nothing shows up in the console. Do I need to configure something in the next.config.js file or is ...

The GET request on the Express route is malfunctioning, causing the Postman request to time out after getting stuck for some

My Express app seems to be experiencing some issues with the GET route. When making a request using Postman, the response gets stuck for a while before fetching. The GET route is properly set up with all necessary request parsers and the app initialized an ...

React Next - ReferenceError: window object is undefined

Within my coding framework, I have implemented two distinct reusable functions that both utilize the window.localStorage.getItem method. The first function, userByToken, encounters an error due to its use of window, while the second function, useValidateTo ...

Tips for creating a React JS static site on a cPanel hosting account

After creating my React JS app with create-react-app configurations, everything was running smoothly in the development build of React. I used the npm build command to generate a build folder for my static (server-less) webpage. Now, my question is how d ...

Utilize forRoot to pass configuration data

When using Angular, I encountered a challenge in passing configuration data to a custom library. Within the user's application, they are required to provide config data to my library through the forRoot method: // Importing the custom library import ...

Make sure to call the loader function in React Router only when there are path params present

I'm currently implementing the new React Router, utilizing loader functions to fetch data based on the loaded element. My goal is to have certain APIs called regardless of the route, with additional APIs triggered for specific routes. However, I&apos ...

Is it possible to attach the payload to the beginning of a slice in the extraReducer using React Toolkit?

Using createSlice, I have created a slice and want to add the payload to the root of this slice. If we consider this slice as "payments" and the initial state is an empty object ({}), my goal is to store all payments inside this object in arrays. const ini ...

What is the best way to initiate a refetch when the need arises to follow a different path?

I have encountered a situation where I am able to pass the refetch function on a child component. However, an issue arises when transitioning to another page and implementing redux. This is particularly problematic when attempting to open a dialog for a ne ...

Dealing with CSS specificity issues when incorporating material-ui for React into a WordPress plugin

Struggling to integrate material-ui for react in a wordpress plugin due to conflict with wordpress's styling in forms.css file. Looking for a solution that doesn't require complete restyling of material-ui components to override the default style ...

What is the best way to generate multiple progress bars by leveraging a for loop?

Exploring the code snippet below, I've been creating a progress bar that reacts to specific data input in array form. However, the issue I've encountered is that the code only generates a single progress bar. How can I incorporate this into my f ...

How does the `useTracker` function determine which data subscriptions to establish?

As I delve into the Meteor basic tutorial, I am facing challenges with the automatic update of the "task list" when inserting an item. Hence, I decided to troubleshoot. The primary app component utilizes the useTracker function hook to "subscribe" to chan ...

The scroll bar of the Bootstrap modal keeps playing peekaboo every time a new modal is triggered

After trying numerous solutions without success, I am posting this question regarding an issue with the scrolling behavior of Bootstrap modals. Here is the scenario: I have 2 Modals: Modal-1 and Modal-2. When a user is inputting information in Modal-1 ...

Have there been any instances of combining AngularJS, ASP.NET-WebApi, OData, Breeze.js, and Typescript?

I am attempting to combine different technologies, but I am facing challenges as the entity framework meta-datas are not being consumed properly by breeze.js. Despite setting up all configurations, it's proving to be a bit tricky since there are no ex ...

What is the proper way to add comments within CSS code inline?

Can anyone provide instructions on how to comment an inline css property, such as height, in the following code snippet? <div style="width:100%; height:30%;"> Any help is appreciated. Thank you! ...

Eliminating the admin-bar.php styling in a WordPress theme

Currently, I am working on developing my very first WordPress template. I have encountered an issue with the top navigation being pushed down by a specific style rule: html { margin-top: 32px !important; } After investigating further, I discovered that t ...

Filtering through an array object with PrimeNG

Is it feasible to utilize an array of objects for filtering data in a table? I'm currently using Angular 6 and PrimeNG 7. This is how my p-table appears: <p-table #table class="ui-table ui-table-responsive" [value]="arrays" [columns]="cols" > ...

Can bootstrap columns be offset only on large devices?

Is there a way I can have the title column float to the right side of the page only on medium devices and larger screens, while keeping it centered for smaller devices like phones? Any advice is appreciated! <div class="section header"> <div ...

Why did my compilation process fail to include the style files despite compiling all other files successfully?

As English is not my first language, I kindly ask for your understanding with any typing mistakes. I have created a workspace with the image depicted here; Afterwards, I executed "tsc -p ." to compile my files; You can view the generated files here Unf ...

Error: Unable to locate module: File not found at './data:application/font-woff;charset=utf-8;base64,`

Encountered an issue with swiper in my Next.js project. "next": "^12.0.3", "swiper": "^7.2.0" I have the specified versions installed and need a solution to resolve this error. Error message: Module not found - Ca ...