Making package with React + TS + Storybook + Rollup problems - reactjs

I'm making my own design system with React + Typescript + Storybook + Rollup.
Before publishing my lib to NPM, I wanted to test this lib in my local env.
I built my project and install like npm i ../my_lib.
I wanted to import my Button component, so I wrote a Login page.
import React from "react";
import { Button } from "#myLib/ui/src";
const Login = () => {
return (
<div>
<Button>Hello</Button>
</div>
);
};
export default Login;
In VSCode, there's no error.
But I started my dev server, this message occured.
Module parse failed: Unexpected token (1:7)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
> export interface IconProps {
| size?: number;
| fillColor?: string;
I think the rollup.config.js has problem. I tried many cases, but only interface got error.
Here is my rollup.config.js.
import commonjs from 'rollup-plugin-commonjs';
import resolve from 'rollup-plugin-node-resolve';
import babel from 'rollup-plugin-babel';
import typescript from 'rollup-plugin-typescript2';
import pkg from './package.json';
import svgr from '#svgr/rollup';
import url from 'rollup-plugin-url';
import peerDepsExternal from 'rollup-plugin-peer-deps-external';
const extensions = ['.js', '.jsx', '.ts', '.tsx'];
process.env.BABEL_ENV = 'production';
export default {
input: './src/index.ts',
plugins: [
peerDepsExternal(),
resolve({ extensions }),
commonjs({
include: 'node_modules/**',
}),
typescript({ useTsconfigDeclarationDir: true }),
babel({ extensions, include: ['src/**/*'], runtimeHelpers: true }),
url(),
svgr(),
],
output: [
{
file: pkg.main,
format: 'es',
},
],
};
Is there any wrong field in my config file?

Related

How to build a project with vite and create mode production to use in nextjs projects?

How to build a project with vite and create mode production to use in nextjs projects?
Because after build production and install my project vite in project with next ssr
Show a error document is not defined
import { resolve, isAbsolute } from 'path';
import react from '#vitejs/plugin-react';
import { defineConfig } from 'vite';
import dts from 'vite-plugin-dts';
import tsConfigPaths from 'vite-tsconfig-paths';
import * as packageJson from './package.json';
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
react(),
tsConfigPaths(),
dts({
insertTypesEntry: true,
include: ['src'],
}),
],
base: '',
build: {
lib: {
entry: resolve(__dirname, 'src/index.ts'),
name: 'index',
formats: ['es', 'cjs'],
fileName: (format: string) => `index.${format}.js`,
},
rollupOptions: {
external: [...Object.keys(packageJson.peerDependencies)],
},
assetsInlineLimit: 0,
},
});
Expect a fix this error

Create a UI package with Emotion and consume it with Next.js application

Problem:
We've built a UI package using React, Emotion, and Vite. We're consuming it in a Next.js app.
But when we import a component, we get the following ServerError -
TypeError: Cannot read properties of null (reading 'registered')
Seems like the cache object is null on the server.
Even when adding <CacheProvider> to the Next.js app, we still get the same error.
Extra information:
Here's how our vite.config.js loos like -
import { defineConfig } from 'vite';
import react from '#vitejs/plugin-react';
import packageJson from './package.json';
export default defineConfig({
plugins: [
react({
jsxImportSource: '#emotion/react',
babel: {
plugins: ['#emotion/babel-plugin'],
},
}),
],
esbuild: {
jsxInject: "import React from 'react'",
},
build: {
outDir: 'lib',
lib: {
entry: './src/index',
formats: ['esm'],
fileName: (format) => `ui.${format}.js`,
},
rollupOptions: {
// Externalize dependencies that shouldn't be bundled into library
external: [...Object.keys(packageJson.peerDependencies)],
},
},
});

css module support using react Rolllup

I'm working on building out a react package (not app) and have run into my introduction to using rollup which, as I understand it, the equivalent to using webpack for react app development.
As I'm moving my code over I've run into a snag where I can't seem to work out the configuration to allow for css/scss module support, e.g.,
import React from "react";
import styles from "./Button.css"; <--- TS2307: Cannot find module './Button.css' or its corresponding type declarations.
my configuration looks like this:
import resolve from "#rollup/plugin-node-resolve";
import commonjs from "#rollup/plugin-commonjs";
import typescript from "#rollup/plugin-typescript";
import postcss from "rollup-plugin-postcss";
import dts from "rollup-plugin-dts";
const packageJson = require("./package.json");
export default [
{
input: "./src/index.ts",
output: [
{
file: packageJson.main,
format: "cjs",
sourcemap: true
},
{
file: packageJson.module,
format: "esm",
sourcemap: true
}
],
plugins: [
resolve(),
postcss({
extract: false,
modules: true,
use: ['sass'],
}),
commonjs(),
typescript({ tsconfig: "./tsconfig.json" })
]
},
{
input: "dist/esm/types/index.d.ts",
output: [{ file: "dist/index.d.ts", format: "esm" }],
plugins: [dts()],
external: [/\.(css|less|scss)$/]
}
];
but I can't get passed the error:
TS2307: Cannot find module './Button.css' or its corresponding type declarations.
my web research has found some attempts at solving this, but nothing has worked. I can drop the css directly on the component:
import React from "react";
import "./Button.css";
But the assignment doesn't work. Any ideas on solution?

Usage of recoil in custom NPM component

I'm trying to use recoil in a custom npm component so that I can publish and use it in an application but upon usage getting error as below:
Invalid hook call. Hooks can only be called inside of the body of a function component...
> const useStoreRef = () => useContext(AppContext);
I'm using following rollupjs to build package:
rollup.config.js
import babel from "#rollup/plugin-babel";
import commonjs from "#rollup/plugin-commonjs";
import resolve from "#rollup/plugin-node-resolve";
import external from "rollup-plugin-peer-deps-external";
import postcss from "rollup-plugin-postcss";
import postcssImport from "postcss-import";
import packageJSON from "./package.json";
const input = "./src/index.js";
const PLUGINS = [
babel({
exclude: "node_modules/**",
}),
external(),
resolve({
jsnext: true,
main: true,
browser: true,
}),
commonjs(),
postcss({
plugins: [postcssImport()],
}),
];
export default [
// CommonJS
{
input,
output: {
file: packageJSON.main,
format: "cjs",
sourcemap: true,
},
plugins: PLUGINS,
},
];
.babelrc
{
"presets": ["#babel/preset-env", "#babel/preset-react"],
"plugins": ["#babel/plugin-proposal-class-properties"]
}
src/index.js
import React, { useEffect, useState, useCallback } from "react";
import { useRecoilState, useSetRecoilState } from "recoil";
import {atomState} from '../recoil/atom';
const Component = () => {
const [state, setState] = useRecoilState(atomState);
...
...
return <div>
...
{state}
...
</div>
}
In application, the published component is used as below:
App.js
import {Component} from "NPM_PACKAGE_NAME";
import {RecoilRoot} from "recoil";
<RecoilRoot>
<Component />
</RecoilRoot>
Please help resolve this. I'm new to recoil js. Thanks in advance.
Note: I'm using yarn link to use the package
I saw a few GitHub issues on this. Apparently this problem exists only if you are using yarn link to use package in your application. If I am publishing to npm registry and use, it works as expected.

Rollup React Library Output Multiple Build Folders?

I have created a React Library with rollup, however, I have a large number of components that get exported so the file size is relatively large.
So in a project where I import the library doing the following;
import { ComponentExampleOne, ComponentExampleTwo } from 'my-react-library';
It imports the whole index file outputted via rollup (including all other components and any 3rd party dependencies), so when a user first hits the page with the import above they need to download the whole file, which is a lot bigger than I would like it to be.
For the likes of lodash where I just want to access a single function and not the entire library, I would do the following;
import isEmpty from 'lodash/isEmpty';
I want to achieve similar functionality with rollup so I can do something like
import { ComponentExampleOne } from 'my-react-library/examples';
import { ButtonRed } from 'my-react-library/buttons';
So I only import what is exported in the index.js file within an examples and buttons folder with this is as my folder structure in my library.
my-react-library/
-src/
--index.js
--examples/
---ComponentExampleOne.js
---ComponentExampleTwo.js
---ComponentExampleThree.js
---index.js
--buttons/
---ButtonRed.js
---ButtonGreen.js
---ButtonBlue.js
---index.js
I have no idea to achieve this with rollup?
This is my current rollup.config.js
import babel from 'rollup-plugin-babel';
import peerDepsExternal from 'rollup-plugin-peer-deps-external';
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import postcss from 'rollup-plugin-postcss';
import filesize from 'rollup-plugin-filesize';
import localResolve from 'rollup-plugin-local-resolve';
import json from 'rollup-plugin-json';
import pkg from './package.json';
import externals from 'rollup-plugin-node-externals';
import builtins from 'rollup-plugin-node-builtins';
import globals from 'rollup-plugin-node-globals';
import image from 'rollup-plugin-inline-image';
import { terser } from 'rollup-plugin-terser';
const config = {
input: 'src/index.js',
watch: {
chokidar: {
usePolling: true,
paths: 'src/**'
}
},
output: [
{
file: pkg.browser,
format: 'umd',
name: 'Example'
},
{
file: pkg.main,
format: 'cjs',
name: 'Example'
},
{
file: pkg.module,
format: 'es'
},
],
external: Object.keys(pkg.peerDependencies || {}),
plugins: [
globals(),
builtins(),
externals(),
babel({ exclude: 'node_modules/**', presets: ['#babel/env', '#babel/preset-react'] }),
commonjs({
include: "node_modules/**",
namedExports: {
// left-hand side can be an absolute path, a path
// relative to the current directory, or the name
// of a module in node_modules
'node_modules/formik/node_modules/scheduler/index.js': ['unstable_runWithPriority'],
}
}),
peerDepsExternal(),
postcss({ extract: true }),
json({ include: 'node_modules/**' }),
localResolve(),
resolve({
browser: true,
dedupe: ['react', 'react-dom'],
}),
filesize(),
image(),
terser()
]
};
export default config;
Any help would be greatly appreciated.
You don't really need to do that if you use named exports and any modern bundler for building the app.
When Rollup detects you are not using some export it will be removed due to tree-shaking.
If you still want to do it pass an object with the different entries you want to the input option:
// ...
const config = {
input: {
examples: 'examples/entry/file.js',
buttons: 'buttons/entry/file.js'
},
// ...
}

Resources