Tips for integrating CSS modules with TypeScript and Rollup

I am currently working on developing a TypeScript library to be shared across various websites. It's been a while since I last worked on something like this. Here is a snippet from my tsconfig.json:

{
  "compilerOptions": {
    "target": "es6",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "baseUrl": "."
  },
  "include": ["src/**/*.ts", "src/**/*.tsx"],
  "exclude": ["node_modules"],
  "ts-node": {
    "compilerOptions": {
      "module": "commonjs"
    }
  }
}

In addition, here is an excerpt from my rollup.config.js:

import pkg from './package.json'
import dts from 'rollup-plugin-dts'
import esbuild from 'rollup-plugin-esbuild'
import autoprefixer from 'autoprefixer'
import postcss from 'rollup-plugin-postcss'
import peerDepsExternal from 'rollup-plugin-peer-deps-external'

const name = pkg.main.replace(/\.js$/, '')

export default [
  {
    preserveModules: true,
    input: 'src/index.ts',
    plugins: [
      peerDepsExternal(),
      postcss({
        plugins: [autoprefixer()],
        sourceMap: true,
        extract: false,
        modules: true,
      }),
      esbuild({
        include: /\.[jt]sx?$/,
        exclude: /node_modules/,
        sourceMap: true,
        target: 'es6',
        jsx: 'transform',
        jsxFactory: 'React.createElement',
        jsxFragment: 'React.Fragment',
      }),
    ],
    output: [
      {
        dir: 'dist',
        exports: 'default',
        format: 'cjs',
        sourcemap: true,
      },
    ],
    external: ['react', 'react-dom'],
  },
  {
    input: 'src/index.ts',
    plugins: [dts()],
    output: {
      file: `${name}.d.ts`,
      format: 'es',
    },
  },
]

Furthermore, here is part of my package.json:

{
  "name": "@myorg/mylib.js",
  "version": "0.0.1",
  "devDependencies": {
    "autoprefixer": "^10.4.11",
    "esbuild": "^0.15.7",
    "postcss": "^8.4.16",
    "rollup": "^2.79.0",
    "rollup-plugin-dts": "^4.2.2",
    "rollup-plugin-esbuild": "^4.10.1",
    "rollup-plugin-peer-deps-external": "^2.2.4",
    "rollup-plugin-postcss": "^4.0.2",
    "typescript": "^4.8.3"
  },
  "main": "dist/index.js",
  "license": "MIT",
  "scripts": {
    "build": "yarn rollup -c"
  },
  "peerDependencies": {
    "classnames": "^2.3.2",
    "next": "^12.3.0",
    "react": "^18.2.0"
  },
  "dependencies": {
    "@types/react": "^18.0.20",
    "classnames": "^2.3.2"
  }
}

Lastly, when trying to load the src/index.ts, I encountered an issue with CSS modules within Rollup:

import Button from './components/Button'

export default {
  Button,
}

The Button component references these two files:

import React from 'react'
import styles from './index.module.css'

export default function Button() {
  return <button className={styles.button}>hello</button>
}

The content of index.module.css is as follows:

.button {
  background: red;
}

However, upon running yarn build, I encountered the following error:

yarn run v1.22.17
$ yarn rollup -c
$ /my/project/node_modules/.bin/rollup -c

src/index.ts → dist...
created dist in 190ms

src/index.ts → dist/index.d.ts...
src/components/Button/index.tsx(4,20): error TS2307: Cannot find module './index.module.css' or its corresponding type declarations.

[!] (plugin dts) Error: Failed to compile. Check the logs above.
src/components/Button/index.tsx
Error: Failed to compile. Check the logs above.
    at error (/my/project/node_modules/rollup/dist/shared/rollup.js:198:30)
    at throwPluginError (/my/project/node_modules/rollup/dist/shared/rollup.js:21919:12)
    at Object.error (/my/project/node_modules/rollup/dist/shared/rollup.js:22641:20)
    at Object.error (/my/project/node_modules/rollup/dist/shared/rollup.js:22096:42)
    at Object.transform (/my/project/node_modules/rollup-plugin-dts/dist/rollup-plugin-dts.cjs:1618:26)
    at /my/project/node_modules/rollup/dist/shared/rollup.js:22848:40

Any suggestions on how to resolve the compilation issue related to CSS modules in Rollup?

Answer №1

My problem with the @import was fixed by eliminating the file extension.

Instead of:

@import 'some.css'

try using this:

@import 'react-toastify/dist/ReactToastify'

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

Troubleshooting the Gutter Problem in jQuery Isotope and Masonry

Currently, I am utilizing the Isotope jQuery plugin. While it is a fantastic tool, I am encountering a minor issue with aligning items in masonry mode. The width of my container is 960px, and I aim to have 4 items perfectly aligned as if they were adhering ...

Exploring innerHTML in JavaScript for event listening

Two code snippets were tested, one worked as expected while the other didn't produce the desired result. The goal was to display a different text every time a user clicked on a button. However, the unsuccessful code always displayed err, with no chang ...

Choose a text input form field simultaneously?

Is it possible to create a select field that also acts as an input form simultaneously? I need the options in this hybrid field to range from 0.01 to 10.00, while ensuring it always displays 2 decimal places. Curious how I can achieve this functionality ...

Creating interactive JSON objects through the use of JavaScript and AngularJS

When using AngularJS to build a dynamic JSON from server data, I encountered an issue where my current declaration only works if the server data contains one item in the object array. How can I modify this to handle multiple items dynamically? $scope.it ...

Is there a way to display incoming chat messages on the chat box without requiring a page refresh using socket.io?

Having trouble resolving an issue with my application hosted on wpengine, built using WordPress, vue.js, and socket.io for chat functionality. The main concern is that new messages posted in the chatbox do not display until the page is refreshed. I'm ...

The functionality for the "OnChange" event in the <html:select> field does not seem to be functioning properly

My JavaScript function isn't functioning properly. I can't see any alert messages on my webpage. Can someone please assist me? Below is my HTML code function checkProjectStatus() { alert("Helloo"); var dropdownType = document.getElementById( ...

Using PHP's $_GET with an Ajax/Jquery Request

I've been struggling to set a variable $id=$_GET["categoryID"] and can't seem to make it work. I suspect it's related to the Ajax request, but I'm unsure how to format it correctly to work with the request for my mysql query. Any assist ...

Tips on dividing and recycling mongodb connection in Node.js

I am currently troubleshooting the connection to MongoDB using Node.js. The code I have in a file named mongodb.js is as follows: const mongoClient = require('mongodb').MongoClient; const env = process.env.NODE_ENV || 'development'; co ...

Modifying various items depending on the variable's value

I'm attempting to adjust various variables depending on which button the user clicks. For instance, there are three buttons: <button id="button1" onclick="isClicked(this.id)">B1</button> <button id="button2" onclick="isClicked(this.id) ...

Organizing your project with VueJS, VuelidateJS, and NodeJS/Express for optimal structure

Primarily, I specialize in developing intranet sites and web front-ends for embedded devices using NodeJS. Currently, all my code is contained within one NPM package. I have NodeJS running behind Nginx, allowing Nginx to serve css/image/client-side-javasc ...

What is the reason behind the lack of covariance in an interface when using a type of T[keyof T]?

I'm attempting to enable type covariance so that Type<Cat> can be treated as a Type<Animal>, for instance, treating a list of Cats as a list of Animals. However, using the type T[keyof T] in a method within the Type interface seems to hind ...

Using JQuery to dynamically add a third expandable row to a table

In my JQuery code (within documentReady), I utilize DataTable to create a table. table = $('#transaction').DataTable({ "ajax": { "url": "servicingTransactionsLoad.do", "type": "GET", " ...

Automatically reconstructing local packages when changes occur

After installing a local package using npm local paths, I am looking for a way to automatically rebuild or re-install the package whenever I make changes to the file. Can anyone help me with this? I have searched online extensively but haven't come a ...

Utilizing local storage, store and access user's preferred layout options through a click function

Exploring the realm of localstorage for the first time, I am considering its use to store a specific ID or CLASS from my css file. This stored information would then be utilized to render a selected layout (grid/list) in the user's browser upon their ...

Determine if there is any item in a collection that includes a specified attribute found in a separate set

I've attempted various solutions for this issue and have searched around but I'm unable to get it to work. I am dealing with 2 arrays and need to verify if any of the items in one array contain any of the strings from the other array. const ste ...

Spartacus storefront is having trouble locating the .d.ts file when using Angular/webpack

Seeking help from the SAP Spartacus team. Encountering errors while developing a Spartacus component, specifically with certain Spartacus .d.ts definition files that cannot be resolved. The issue is reproducible in this Github repository/branch: This pr ...

Having difficulty showing the successful JSON output in either the view or an alert

In my CodeIgniter project, I have three input fields named name, emp_id, and crm_id. I enter the id value and send it to the controller via AJAX and JSON to retrieve all information related to that id. The issue is that while I can see the correct output i ...

Ways to remove code from production during build process?

Is there a way to omit typescript code from getting bundled by webpack during build process? Let's say I have the following line of code in my app.ts file (a nodejs application): const thisShouldNotBeInProductionBundleJustInDevBundle = 'aaaaaaa ...

ID could not be retrieved from the checkbox

I am facing an issue with my HTML checkboxes. The ids are generated from an angular ng-repeat, but when I try to collect the id for use, it always returns as undefined. $("input:checkbox.time-check-input").each(function () { var ruleUnformatted = ""; ...

Differences in JSON parsing behavior between Chrome and Firefox

I encountered an unusual issue with the return error of JSON.parse() function: I am using this function to validate a JSON string obtained from a web-based editor. The string is pre-manipulated using the JSON.stringify() function. To be more specific: JSO ...