Webpack5打包TS React组件库遇“module has no exports”错误
我基于现有React UI组件库开发TypeScript React UI组件库,采用Webpack 5进行打包。在Button组件中引入component-library的CLButton后,执行webpack命令出现警告:export 'CLButton'未在'component-library'中找到(模块无导出)。
组件代码(Button.tsx)
import { CLButton } from 'component-library' import { ButtonProps } from './Button.types' const Button = (props: ButtonProps): JSX.Element => { const { title = 'Hello, World!', body = 'I am the first component of this lib', } = props return ( <div> <h1>{title}</h1> <p>{body}</p> <CLButton /> </div> ) } export default Button
tsconfig.json
{ "compilerOptions": { "target": "ES6", "lib": ["DOM", "ESNext"], "jsx": "react-jsx", "module": "ESNext", "rootDir": "src", "moduleResolution": "node", "baseUrl": "/src", "paths": { "components": ["src/components/*"] }, "declaration": true, "sourceMap": true, "outDir": "dist", "noEmit": false, "isolatedModules": true, "allowSyntheticDefaultImports": true, "esModuleInterop": true, "forceConsistentCasingInFileNames": true, "strict": true, "noImplicitAny": true, "strictNullChecks": true, "noImplicitThis": true, "noImplicitReturns": true, "skipLibCheck": true }, "include": [ "globals.d.ts", "src/**/*", "index.ts" ], "exclude": [ "node_modules", "build", "dist", "webpack", "jest" ] }
webpack.config.js
import path from 'path' import { fileURLToPath } from 'url' const __filename = fileURLToPath(import.meta.url) const __dirname = path.dirname(__filename) export default { entry: { 'my-component-library': './src/index.ts', 'my-component-library.min': './src/index.ts', }, mode: 'production', output: { path: path.resolve(__dirname, 'dist'), filename: '[name].js', library: 'my_component_library', }, resolve: { extensions: ['js', '.ts', '.tsx'], }, module: { rules: [ { test: /\.(ts|tsx)$/, use: ['ts-loader'], include: path.resolve(__dirname, './src'), exclude: [/node_modules/, /\.stories.tsx$/, /\.test.tsx$/], }, { test: /\.scss$/, use: ['style-loader', 'css-loader', 'sass-loader'], include: path.resolve(__dirname, './src'), }, ], }, externals: { react: 'react', 'react-dom': 'react-dom', }, }
错误信息
WARNING in ./src/components/Button/Button.tsx 5:107-116 export 'CLButton' (imported as 'CLButton') was not found in 'component-library' (module has no exports) @ ./src/components/Button/index.ts 1:0-35 1:0-35 @ ./src/components/index.ts 1:0-45 1:0-45 @ ./src/index.ts 1:0-29 1:0-29
可能的原因及排查方向
- 导出方式不匹配:
component-library可能采用默认导出(export default CLButton),而你使用了命名导入语法,导致Webpack无法识别对应导出。可以尝试改为import CLButton from 'component-library'验证。 - 组件库安装或路径问题:检查
node_modules中是否存在component-library,确认包名拼写无错误。如果是本地开发的库,需检查其package.json的main/module/types字段,确保指向的文件正确导出了CLButton。 - Webpack解析配置缺失:当前Webpack的
resolve.extensions未包含.jsx,若component-library的组件文件是.jsx后缀,会导致Webpack无法正确解析。建议添加.jsx到扩展数组中。 - 组件库未预编译:如果
component-library是未转译的TS/TSX源码,Webpack的exclude规则排除了node_modules,导致无法处理该库代码,进而无法识别导出。可修改Webpack配置,将component-library从exclude中移除,或确保该库已预编译为JS。
内容的提问来源于stack exchange,提问作者Gambit2007
相关产品推荐
相关产品推荐

