将用TypeScript编写的react组件发布到npm,但在导入时未定义



我试图将自己用TypeScript编写的react组件发布到npm。我发布得很好,但当我创建了一个新的react项目并导入我构建的npm包时,出现了一些错误:

错误:元素类型无效:应为字符串(用于内置组件(或类/函数(对于复合组件(,但得到:未定义。您可能忘记从文件中导出组件它是在中定义的,或者您可能混淆了默认导入和命名导入。

错误图像

但我确信我没有滥用命名导出和默认导出。所以我认为我的webpack配置或tsconfig可能有问题。

我的webpack.config.json

const path = require('path');
module.exports = {
mode: 'none',
entry: path.join(__dirname, 'src', 'index.tsx'),
target: 'web',
resolve: {
extensions: ['.ts', '.tsx', '.js', '.jsx', '.css']
},
module: {
rules: [
{
test: /.(ts|tsx)$/,
use: "babel-loader",
exclude: '/node_modules/',
},
{
test: /.(ts|tsx)$/,
use: 'awesome-typescript-loader',
exclude: '/node_modules/'
},
{
test: /.css$/i,
use: ['style-loader', 'css-loader'],
},
],
},
output: {
filename: 'index.js',
path: path.resolve(__dirname, 'dist')
}
}

我的tscongig.json

{
"compilerOptions": {
"outDir": "./dist",
"target": "es6",
"module": "commonjs",
"skipLibCheck": true,
"allowSyntheticDefaultImports": true,
"noImplicitAny": false,
"strictNullChecks": false,
"removeComments": true,
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"isolatedModules": true,
"esModuleInterop": true,
"jsx": "react",
"typeRoots": [
"dist/index.d.ts",
"node_modules/@types"
]
},
"include": [
"./src/*",
],
"exclude": [
"node_modules",
"dist"
]
}

软件包.json

{
"name": "myname",
"version": "1.0.42",
"description": "some text",
"main": "dist/index.js",
"types": "dist",
"scripts": {
"build": "webpack --config webpack.config.js --mode production"
},
"repository": {
"type": "git",
"url": "some url"
},
"author": "secret",
"license": "MIT",
"dependencies": {},
"devDependencies": {
"@babel/core": "^7.12.3",
"@babel/preset-env": "^7.12.1",
"@babel/preset-react": "^7.12.1",
"@babel/preset-typescript": "^7.12.1",
"@types/react": "^16.9.53",
"@types/react-dom": "^16.9.8",
"@types/webpack": "^4.41.23",
"awesome-typescript-loader": "^5.2.1",
"babel-loader": "^8.1.0",
"css-loader": "^5.0.0",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"style-loader": "^2.0.0",
"typescript": "^4.0.3",
"webpack": "^5.2.0",
"webpack-cli": "^4.1.0"
}
}

和我的入口点index.tsx

import someComponent from './someComponent';
export { someComponent };

我确信someComponent是从其他文件默认导出的。

有人能帮我解决这个问题吗?

我遇到了这个问题,解决方案是确保在运行npm publish之前先运行npm run build。这是为了确保在发布之前正确生成类型。我在package.json中的脚本如下:

"scripts": {
"start": "webpack serve --mode development",
"build:types": "tsc --emitDeclarationOnly",
"build": "npm run build:types && webpack --mode production",
"refreshVSToken": "vsts-npm-auth -config .npmrc"
},

最新更新