react+ ts + vite3 项目中引用 commonjs 模块的 react 组件,在开发环境使用 vite-plugin-commonjs 插件,不会报错,但在打包是会报一下错误:
其中,commonModule.tsx 是 react 组件,使用 exports 进行导出
// common/commonModule.tsx
function Common() {
return (
<div className='App'>
<h1>Commcon Module</h1>
</div>
)
}
exports.Common = Common
引用 commonModule.tsx 组件
import { useState } from 'react'
import reactLogo from './assets/react.svg'
import './App.css'
import {Common} from './common/commonModule'
function App() {
const [count, setCount] = useState(0)
return (
<div className="App">
<div>
<a href="https://vitejs.dev" target="_blank">
<img src="/vite.svg" className="logo" alt="Vite logo" />
</a>
<a href="https://reactjs.org" target="_blank">
<img src={reactLogo} className="logo react" alt="React logo" />
</a>
</div>
<h1>Vite + React</h1>
<Common />
<div className="card">
<button onClick={() => setCount((count) => count + 1)}>
count is {count}
</button>
<p>
Edit <code>src/App.tsx</code> and save to test HMR
</p>
</div>
<p className="read-the-docs">
Click on the Vite and React logos to learn more
</p>
</div>
)
}
export default App
vite.config.ts 配置如下
// vite.config.ts
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import commonjs from 'vite-plugin-commonjs'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
react(),
commonjs.default(),
]
})
tsconfig.json 配置
{
"compilerOptions": {
"target": "ESNext",
"useDefineForClassFields": true,
"lib": ["DOM", "DOM.Iterable", "ESNext"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "ESNext",
"moduleResolution": "Node",
"resolveJsonModule": true,
"isolatedModules": false,
"noEmit": true,
"jsx": "react-jsx"
},
"include": ["src"],
"references": [{ "path": "./tsconfig.node.json" }]
}
使用 @originjs/vite-plugin-commonjs 插件,配置 build.commonjsOptions,optimizeDeps 这些试过都不行;这个场景在旧项目重构,使用 vite 的时候会遇到,请问哪位大神可以解答下原因,多谢!!
安装@rollup/plugin-commonjs插件,
vite-plugin-commonjs
官方已经说了只能在开发环境下使用,build应该使用rollup
的插件。