Skip to content

Uncaught Error: Calling require for "react" in an environment that doesn't expose the require function. #223

Closed
@QiuYiLiang

Description

@QiuYiLiang

Describe the bug

使用rolldown-vite打包组件库,输出格式为es
在浏览器引入打包后的js,会报错
Uncaught Error: Calling requirefor "react" in an environment that doesn't expose therequire function.
使用vite打包正常

vite.config.ts

import react from '@vitejs/plugin-react-swc'

// https://vite.dev/config/
export default defineConfig({
  build: {
    lib: {
      entry: './src/index.tsx',
      formats: ['cjs', 'es']
    },
    rollupOptions: {
      external: ['react']
    },
    outDir: 'dist',
    minify: false
  },
  plugins: [react()],
})

index.ts

export const Button = () => {
  return <button>test</button>
}

Reproduction

https://stackblitz.com/edit/vitejs-rolldown-vite-r1urwj9h?file=vite.config.js,package.json,index.html

Steps to reproduce

1.打包
pnpm i
pnpm build
2.预览
pnpm dev
3.查看控制台,复现报错

System Info

Uncaught Error: Calling `require` for "react" in an environment that doesn't expose the `require` function.

Used Package Manager

pnpm

Logs

No response

Validations

Metadata

Metadata

Assignees

No one assigned

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions