Webpack构建含TS&JSX的本地共享包时导入函数报错求助
1. 检查模块导出方式
确保shared/utils/withAuth.ts使用具名导出,避免默认导出导致解构错误:
// shared/src/utils/withAuth.ts export const withAuth = (Component) => { // 你的权限校验逻辑 };
不要写成默认导出后再用具名导入(比如export default withAuth然后import { withAuth } from '...'),这种写法会导致webpack识别为undefined。
2. 配置shared包的package.json与TSConfig
2.1 完善shared包的package.json
明确指定模块入口,同时输出CommonJS和ES模块适配webpack解析:
{ "name": "@acme/shared", "main": "dist/index.js", "module": "dist/esm/index.js", "types": "dist/index.d.ts", "scripts": { "build": "tsc && tsc --module ESNext --outDir dist/esm" } }
2.2 开启JSX支持与类型声明
修改shared包的tsconfig.json,确保支持React JSX编译并生成类型声明:
{ "compilerOptions": { "jsx": "react-jsx", // React 17+用这个,旧版本用"react" "declaration": true, "outDir": "./dist", "module": "CommonJS", "target": "ES6", "moduleResolution": "Node", "esModuleInterop": true, "skipLibCheck": true }, "include": ["src/**/*"] }
3. 调整client包的Webpack配置
让webpack能正确解析@acme/shared的路径与TS/TSX文件:
// client/webpack.config.js const path = require('path'); module.exports = { // 其他配置... resolve: { extensions: ['.ts', '.tsx', '.js', '.jsx'], alias: { '@acme/shared': path.resolve(__dirname, '../shared/src'), // 直接指向源码或dist目录均可 }, modules: ['node_modules', path.resolve(__dirname, '../')] }, module: { rules: [ { test: /\.(ts|tsx)$/, use: 'ts-loader', exclude: /node_modules\/(?!@acme\/shared)/ // 不要排除shared包的源码(如果指向src的话) } ] } };
4. 规范构建流程
- 每次修改shared包后,先执行
yarn workspace @acme/shared build编译源码,再构建client包 - 可以在client的package.json中添加预构建脚本,自动触发shared包的构建:
{ "scripts": { "prebuild": "yarn workspace @acme/shared build", "build": "webpack --mode=development" } }
5. 可选:统一导出入口
如果深层路径导入仍有问题,可以在shared包的src/index.ts中统一导出所有模块:
// shared/src/index.ts export * from './utils/withAuth'; export * from './components/Header'; // 导出React组件 export * from './hooks/useUser'; // 导出自定义钩子
之后在client中可以直接用import { withAuth } from '@acme/shared';导入,避免深层路径解析问题。
内容的提问来源于stack exchange,提问作者user1275493
相关产品推荐
相关产品推荐

