DEV Community

Discussion on: Create a React component library with Vite and Typescript

Collapse
 
njavilas2015 profile image
njavilas2015 • Edited

good evening your article fell from the sky, I would like to share an improvement

import react from '@vitejs/plugin-react';
import { readFile } from 'node:fs/promises';
import path from 'node:path';
import { defineConfig, UserConfigExport } from 'vite';
import dts from 'vite-plugin-dts';

const App = async (): Promise<UserConfigExport> => {

    var name: string = 'replaceme';

    const data: string = await readFile(path.join(__dirname, 'src', 'lib', 'index.tsx'), { encoding: 'utf-8' })

    const s = data.split('\n')

    for (let x of s.reverse()) if (x.includes('export default')) name = x.replace('export default ', '').replace(" ", "")

    return defineConfig({
        plugins: [
            react(),
            dts({
                insertTypesEntry: true,
            }),
        ],
        build: {
            lib: {
                entry: path.resolve(__dirname, 'src/lib/index.tsx'),
                name,
                formats: ['es', 'umd'],
                fileName: (format) => `lib.${format}.js`,
            },
            rollupOptions: {
                external: ['react', 'react-dom', 'styled-components'],
                output: {
                    globals: {
                        react: 'React',
                        'react-dom': 'ReactDOM',
                        'styled-components': 'styled',
                    },
                },
            },
        },
    });
}

export default App 

Enter fullscreen mode Exit fullscreen mode

Image description

This improvement takes the name of the component that we are exporting, so that it is dynamic to obtain the name to import it into our projects

and it works great!

Image description

I took the liberty of exporting our code as lib by default, so I didn't have to keep renaming the files.

Image description

Collapse
 
nicolaserny profile image
Nicolas Erny

Nice improvements! Thanks :)

Collapse
 
stephyswe profile image
Stephanie

maybe a repo link? i tried your solution but Im not sure how to, or what it suppose to do?