Developing a TypeScript frontend library

I am currently in the process of creating a frontend library consisting of React components and CSS/SCSS.

Specifically, I am looking for:

  • To build a single CommonJS .js file and .css file.
  • To exclude external libraries (e.g. React) from the .js output.
  • The ability to utilize (s)css modules.

My code structure resembles the following:

MyComponent.tsx

import { myComponentStyle } from './MyComponent.scss'

export class MyComponent extends React.Component {
  render() {
    return <div className={myComponentStyle} />
  }
}

MyComponent.scss

.myComponentStyle { /* styles */ }

MyComponent.scss.d.ts (Created by typed-css-modules to satisfy the TypeScript compiler)

export const myComponentStyle: string;

I have an index.ts file that exports these components:

index.ts

export { MyComponent } from './MyComponent.tsx'
// other components

If I do not include styles, a rollup configuration like the one below builds everything as intended:

import commonjs from 'rollup-plugin-commonjs'
import typescript from 'rollup-plugin-typescript2'

const pkg = require('./package.json')

export default {
  input: 'src/index.ts',
  output: [{ file: pkg.main, format: 'cjs', sourcemap: true }],
  external: [],
  plugins: [
    typescript({ useTsconfigDeclarationDir: true }),
    commonjs(),
  ],
}

However, I am having difficulties with handling CSS. I attempted using both rollup-plugin-postcss and rollup-plugin-postcss-modules, but neither of them worked.

Therefore, my query is:

  • Is there a method (perhaps an example) on how to configure this setup with Rollup?
  • If not, are there any alternative approaches to generate the desired single .js and .css outputs (via webpack or any other build system)?

Answer №1

You have the option to:

  • utilize the external feature to exclude specific imports
  • employ rollup-plugin-sass for creating a bundle.css.

For more information on using Rollup's external, visit here

// rollup.config.js
import commonjs from 'rollup-plugin-commonjs'
import typescript from 'rollup-plugin-typescript2'
import sass from 'rollup-plugin-sass'

const pkg = require('./package.json')

export default {
    input: 'src/index.ts',
    output: [{ file: pkg.main, format: 'cjs', sourcemap: true }],
    external: Object.keys(pkg.dependencies), // OR specify an array: ['react' /* , ...etc */]
    plugins: [
        sass({
            output: 'dist/bundle.css'
        }),
        typescript({ useTsconfigDeclarationDir: true }),
        commonjs(),
    ],
}

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

Incapable of utilizing CSS Custom Properties (also known as CSS Variables) in conjunction with SASS @if Conditional Statements

I'm attempting to transfer CSS Custom Properties to a SASS Mixin. I can successfully use the variables directly in the desired styling. However, there seems to be a problem when utilizing a variable within an If statement. Here's an example of t ...

Should one prioritize learning TypeScript over diving into Angular2?

Should I prioritize learning TypeScript before diving into AngularJS 2? ...

The border bottom effect in Hover.css is malfunctioning when used in the Opera browser

I've implemented a hover effect using hover.css that works perfectly in all browsers except Opera. Surprisingly, the effect only seems to work in Opera when I remove the following properties: -webkit-transform: perspective(1px) translateZ(0); transf ...

What is the process for importing a file with an .mts extension in a CJS-first project?

Here's a snippet from a fetchin.mts file: import type { RequestInfo, RequestInit, Response } from "node-fetch"; const importDynamic = new Function("modulePath", "return import(modulePath);") export async function fetch(u ...

Angular 4 scatter chart with multiple data points using Google charts

I'm currently developing a scatter graph in Angular 4 using ng2-google-charts from https://www.npmjs.com/package/ng2-google-charts It seems like this is essentially a wrapper for Google Chart Service. The graph looks great with a few values, but whe ...

Applying the `lean` method to Mongoose queries that retrieve arrays in TypeScript

When working with two Mongoose queries, I made the decision to utilize the .lean() method on both of them. It appears that using .lean() on a query that returns a single document works well: let something:Something; SomethingDocument.findOne({_id:theId}) ...

Converting JSON to TypeScript in an Angular project

Within my Angular project, I have an HTTP service that communicates with a web API to retrieve JSON data. However, there is a discrepancy in the naming convention between the key in the JSON response (e.g., "Property" in uppercase) and the corresponding pr ...

Troubleshooting image upload issues with AWS S3 in Next.js version 13

I encountered a consistent problem with using the AWS SDK in NextJS to upload images. I keep getting error code 403 (Forbidden). Could there be other reasons why this error is occurring besides the accessKeyId and secretAccessKey being invalid? Below is my ...

Inquiry regarding Typescript's array of types

While researching how to declare arrays of types online, I came across the following example: arrayVar: Array<Type> Seems simple enough, so I attempted to declare my variable like this: transactions: Transactions = { total : 0, list: Array<Transa ...

What is the best way to bind the value of total when working with forms and the bind method?

I am working on a form where I need to pass the value of total. Regarding the total: I have successfully passed the value of the cart, which is an array. const [total, setTotal] = useState<number | undefined>(undefined); const calculateTotal = () ...

React: Switching PopUp causes the entire component to be re-rendered

Currently, I am in the process of familiarizing myself with React, so I appreciate your patience. I am developing a component using MaterialUI which consists of a grid and a PopOver. A basic mockup of this component is as follows: export const Overview ...

Prevent duplicate API calls in React with TypeScript

Upon page load, it is important to extract the value from the URL and send it to the API. However, due to changes in the state of parent objects, the API call is triggered three times when it should ideally only be called once. import React, {useContext ...

Encountering issues while attempting to execute node-sass using npm

Currently, I'm attempting to execute node-sass using npm. Displayed below is my package.json: { "name": "my-project", "version": "1.0.0", "description": "Website", "main": "index.js", "scripts": { "sass": "node-sass -w scss/ -o dist ...

Sharing data between two Angular 2 component TypeScript files

I'm facing a scenario where I have two components that are not directly related as parent and child, but I need to transfer a value from component A to component B. For example: In src/abc/cde/uij/componentA.ts, there is a variable CustomerId = "sss ...

What are the optimal strategies for managing various components within an Angular (2) Web application?

I am seeking advice on Angular 2+ Webapps and have a few questions. What is the recommended approach for managing a publicly available info page, an authentication page, and a protected page for signed-in users? Should I consider separate Angular Apps ...

Difficulty encountered while trying to link an abstract class with Redux state using redux-thunk

My approach to using redux-thunk and class components in React follows a basic pattern. The code below shows how a class definition MyClass is exported, correctly connected to state through mapStateToProps, and has access to actions from mapDispatchToProps ...

Adding a QR code on top of an image in a PDF using TypeScript

Incorporating TypeScript and PdfMakeWrapper library, I am creating PDFs on a website integrated with svg images and QR codes. Below is a snippet of the code in question: async generatePDF(ID_PRODUCT: string) { PdfMakeWrapper.setFonts(pdfFonts); ...

Check out the selected values in Ionic 3

I am trying to retrieve all the checked values from a checkbox list in an Ionic3 app when clicked. Below is the code snippet: <ion-content padding> <ion-list> <ion-item *ngFor="let item of items; let i= index"> <ion-label>{{i ...

Tips on using class-validator @isArray to handle cases where only a single item is received from a query parameter

Currently, I am attempting to validate a request using class-validator to check if it is an array. The inputs are sourced from query parameters like this: /api/items?someTypes=this This is what my request dto resembles: (...) @IsArray() @IsEn ...

Angular 15 experiences trouble with child components sending strings to parent components

I am facing a challenge with my child component (filters.component.ts) as I attempt to emit a string to the parent component. Previously, I successfully achieved this with another component, but Angular seems to be hesitant when implementing an *ngFor loop ...