如何在Vite项目中导入本地包?解决导出命名不存在报错
问题:Vite导入本地CommonJS构建库时出现导出不存在的错误
问题场景
原本使用react-scripts(已两年未维护且停留在TypeScript v4),切换到Vite.js后,通过package.json的dependencies添加本地库:"my-local-lib": "file:../my-local-lib"。当尝试导入:
import { CONTACT_EMAIL } from 'my-local-lib/dist/constants'
浏览器控制台报错:
hmr.ts:247 SyntaxError: The requested module '/@fs/Users/JohnDoe/Documents/my-local-lib/dist/constants.js' does not provide an export named 'CONTACT_EMAIL' (at App.jsx:6:10)
排查发现:
- 本地库源码
src/constant.js:export const CONTACT_EMAIL = 'example@example.com'; - 编译后的
dist/constant.js(tsc构建):
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CONTACT_EMAIL = 'contact@handballdashboard.com'; //# sourceMappingURL=constants.js.map
Vite基于ES模块规范处理导入,但实际读取的是CommonJS格式的编译文件,导致ES模块的解构导入无法识别CommonJS的exports属性。
问题复现步骤
pnpm create vite my-react-app --template reactcd my-react-apppnpm add ../my-local-libpnpm install
本地库的TypeScript配置:
{ "compilerOptions": { "target": "es2019", "jsx": "react-jsx", "module": "commonjs", "rootDir": "./src", "sourceMap": true, "declaration": true, "outDir": "./dist", "esModuleInterop": true, "forceConsistentCasingInFileNames": true, "strict": true, "skipLibCheck": true } }
解决方案
方案1:修改本地库为输出ES模块(推荐)
调整本地库的tsconfig.json,将模块格式改为ES模块,让Vite可以直接识别:
{ "compilerOptions": { // 保留其他原有配置 "module": "ESNext", // 改为ES模块格式 "moduleResolution": "NodeNext" // 配合ES模块的解析逻辑 } }
重新构建本地库:tsc,之后在项目中可以简化导入路径(建议在本地库的package.json中配置main或exports指向dist文件):
import { CONTACT_EMAIL } from 'my-local-lib/constants'
方案2:在Vite中配置转译本地CommonJS库
如果暂时不想修改本地库的构建格式,可以在vite.config.js中添加配置,让Vite处理本地CommonJS库:
import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' export default defineConfig({ plugins: [react()], optimizeDeps: { include: ['my-local-lib'] }, ssr: { noExternal: ['my-local-lib'] } })
也可以引入@rollup/plugin-commonjs插件转换CommonJS模块:
import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' import commonjs from '@rollup/plugin-commonjs' export default defineConfig({ plugins: [ react(), commonjs({ include: /node_modules|my-local-lib/ }) ] })
方案3:调整导入方式适配CommonJS
直接使用CommonJS兼容的导入方式:
// 方式1:使用require const { CONTACT_EMAIL } = require('my-local-lib/dist/constants') // 方式2:默认导入后解构 import constants from 'my-local-lib/dist/constants' const { CONTACT_EMAIL } = constants
内容的提问来源于stack exchange,提问作者Maxime Lechevallier
相关产品推荐
相关产品推荐

