Develop a React component library and seamlessly integrate it into a Next.js project

Currently, I am in the process of building a component library using react js, vite tailwindcss, and antd. The components function flawlessly when running the project locally or within Storybook. However, upon importing them into another nextjs application, the components lose their styling. Below is the configuration from my package.json:

Package.json

"type": "module",
  "main": "dist/index.umd.js",
  "module": "dist/index.es.js",
  "types": "dist/index.d.ts",
  "exports": {
    ".": {
      "import": "./dist/index.es.js",
      "require": "./dist/index.umd.js",
      "types": "./dist/index.d.ts"
    },
    "./dist/style.css": "./dist/style.css"
  },
  "files": [
    "/dist",
    "/src"
  ],

vite.config.js

import react from '@vitejs/plugin-react';
import path from 'node:path';
import { defineConfig } from 'vite';
import dts from 'vite-plugin-dts';

// https://vitejs.dev/config/
export default defineConfig({
  build: {
    lib: {
      entry: path.resolve(__dirname, 'src/index.ts'),
      name: 'lw-ds',
      fileName: (format) => `index.${format}.js`,
    },
    rollupOptions: {
      external: ['react', 'react-dom'],
      output: {
        globals: {
          react: 'React',
          'react-dom': 'ReactDOM',
        },
      },
    },
    sourcemap: true,
    emptyOutDir: true,
  },
  plugins: [
    react(),
    dts({
      insertTypesEntry: true,
    }),
  ],
});

If you want to see the structure in node_modules after importing it into another application.

I have attempted multiple solutions to resolve this issue. One workaround that seemed to work was creating a components folder within the application and copying the library files there. Even if directly importing from the library, the styling now functions correctly.

Answer №1

Make sure to include the necessary import statement in your upcoming application's _app.tsx or jsx file

import "your-library/dist/style.css";

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

Creating React Components with TypeScript: Ensuring Typechecking in Class and Function Components

Want to ensure typechecking works when defining React Class/Function components in TypeScript? Struggling to find a comprehensive guide on how to do it correctly. I've managed to define the Props and State interfaces, but I'm unsure about how to ...

A method for assigning a single event listener to multiple events in a React component

I find myself in a situation where I have two events, onClick and onSelect, both of which share the same event handler. I am wondering what the most efficient way to handle this scenario would be - should I create a common method and then call the event ...

Guide on how to validate react-multiselect with the use of Yup validation schema

If the multiselect field is empty, the validation message 'Product is required' is not being displayed. How can I validate this field? Here is the validation schema: validationSchema={ Yup.object().shape({ productID: Yup.string().requi ...

What is the best way for me to bring in this function?

Currently, I am in the process of developing a point-of-sale (POS) system that needs to communicate with the kitchen. My challenge lies in importing the reducer into my express server. Despite multiple attempts, I have been unable to import it either as a ...

Displaying an array of objects in the MUI Datagrid interface

I have integrated Redux into my project to retrieve data from the API, and this is a snapshot of the data structure: https://i.stack.imgur.com/jMjUF.png My current challenge lies in finding an effective way to display the information stored within the &a ...

Creating a form in NextJS to securely transfer user input data to MongoDB

Being new to JavaScript, I have a basic understanding and some lack of experience, but I am eager to learn more. Recently, I embarked on a project using NextJS, an efficient framework that integrates with ReactJS. My current challenge lies in creating a si ...

React Drawer triggering excessive re-renders

I am trying to implement a button that, when clicked, will display a Drawer from the bottom. Here is the code snippet I have written: import * as React from "react"; import Box from "@mui/material/Box"; import Drawer from "@mui/mat ...

Ensuring Tab Input Validation in ReactJs with the Help of Form Validator

After browsing through some Q&A, I stumbled upon a thread on the topic of Tabbed form and validation. Although it was close to addressing my issue, it did not provide a solution. I am currently utilizing react-material-ui-form-validator. When multiple ...

Font experiencing FOUT (Flash Of Unstyled Text) with each page reload

Can anyone help me with this issue I am facing? The first time I load everything, it seems fine. https://i.stack.imgur.com/btkN6.png However, after the first time, I see '(ServiceWorker)' as Size but the FOUT (Flash of Unstyled Text) still happ ...

Reactjs slider causes unexpected useState behavior

I created an autoplay Slider with three cards using the useEffect hook. However, the manual "previous" and "forward" buttons are not functioning correctly. The useState function is not updating values as expected, leading to unexpected changes in state. ...

Utilizing the useRef hook in React to retrieve elements for seamless page transitions with react-scroll

I've been working on creating a single-page website with a customized navbar using React instead of native JavaScript, similar to the example I found in this reference. My current setup includes a NavBar.tsx and App.tsx. The NavBar.tsx file consists o ...

The dynamic import() syntax is not compatible with the target environment, preventing the use of external type 'module' in a script

I am currently facing an issue with my React app. The command npm start is working as expected, but when I try to run npm run build, it keeps failing. It's crucial for me to run npm run build in order to deploy the app on a website. I have already sp ...

Tips for utilizing the material ui auto-complete search feature

I am in search of an alternative to material-ui-search-bar because it is no longer being maintained. I have been suggested to try using Material UI's auto complete instead. However, from the examples I've seen, it seems like only text field struc ...

Ways to execute a script from termly on NextJS using JSX

I've been utilizing termly to assist in creating legal terms for a website I'm developing. They provided me with some HTML containing a script, but I am struggling to get it to execute on a page in JSX. I attempted to use both Script and dangerou ...

React does not accept objects as valid children. If you want to render a group of children, make sure to use an array instead

I am in the process of developing a system for document verification using ReactJS and solidity smart contract. My goal is to showcase the outcome of the get().call() method from my smart contract on the frontend, either through a popup or simply as text d ...

Use the useEffect hook to pass newly updated data to a FlatList component

I have encountered an issue with updating a FlatList component in my React Native application. The scenario involves running a graphql query to render items and then refetching the data when a mutation is executed using Apollo's refetch option. Althou ...

Tips for refreshing the direction route in google-maps-react

I have an array of coordinates, and when I add a new coordinate to the array, I want the route direction on the map to update accordingly. This is the code snippet from my googlemap.js file: /* global google */ import React, { Component } from "react ...

When it comes to successful payments, should you use `checkout.session.async_payment_succeeded` or `checkout.session.completed` in the Stripe event?

I'm feeling a little uncertain about the differences between two events: checkout.session.async_payment_succeeded & checkout.session.completed Currently, I am utilizing checkout.session.completed, but I'm wondering if checkout.session.async ...

The type Zustand does not contain a property named 'getState'

I'm currently in the process of integrating shopping cart functionality into Next.js using Zustand. I've encountered a problem when trying to calculate the total number of items in the cart after adding an item or when manipulating the quantity w ...

Data vanishing in upcoming authentication session in test environment

I have encountered an issue with next auth in my next.js project. During development, the session data is lost if the server refreshes or if I switch to another tab and return to it. This forces me to sign out and then sign back in to restore the session d ...