webpack Typescript React组件无法导出

gojuced7  于 2023-08-06  发布在  Webpack
关注(0)|答案(1)|浏览(149)

有几个相关的问题,但没有一个有帮助。。
我想从一个typescript库(我打算在npm上发布)导出一些React组件。
我使用npm link在发布前进行本地测试。
库结构如下所示:
src/components/index.ts:

export { default as SomeComponent } from './SomeComponent';

字符串
src/components/SomeComponent.tsx:

import * as React from 'react';
import '../styles.css';

const SomeComponent: React.FC = () => {
  return <div className="ts-component">test</div>;
};

export default SomeComponent


tsconfig.json:

{
    "compilerOptions": {
      "target": "es6",
      "module": "commonjs",
      "rootDir": "./src/components",
      "outDir": "./dist",
      "declaration": true,
      "sourceMap": true,
      "jsx": "react",
      "baseUrl": "./src",
    },
    "include": ["./src"]
  }


package.json:

{
  "name": "ts-lib-test",
  "version": "1.0.0",
  "description": "dsfsdf",
  "main": "src/components/index.ts",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "peerDependencies": {
    "@types/react": "^18.2.15",
    "@types/react-dom": "^18.2.7",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "typescript": "^5.1.6"
  },
  "devDependencies": {
    "css-loader": "^6.8.1",
    "style-loader": "^3.3.3",
    "ts-loader": "^9.4.4",
    "webpack": "^5.88.2",
    "webpack-cli": "^5.1.4"
  }
}


webpack.config.js:

const path = require('path');

module.exports = {
  entry: './src/components/index.ts',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'index.js',
    library: 'ts-lib-test',
    libraryTarget: 'umd',
    umdNamedDefine: true,
  },
  resolve: {
    extensions: ['.ts', '.tsx', '.json'],
  },
  module: {
    rules: [
      {
        test: /\.(ts|tsx)$/,
        loader: 'ts-loader',
        exclude: /node_modules/,
      },
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader'],
      },
    ],
  },
};


src/styles.css:

.ts-component {
    width: 100px;
    height: 100px;
    margin: 1rem;
    background-color: red;
}


我用npx webpack构建库,然后用npm link链接,然后消费项目看起来像这样:

import './App.css'
import { SomeComponent } from 'ts-lib-test'

function App() {
  return (
    <div className='App'>
      {'This is where the test component goes:'}
      <SomeComponent />
    </div>
  )
}

export default App


这是我能做的最简单的版本,我不能让它工作。当我开始这个项目时
export 'SomeComponent' (imported as 'SomeComponent') was not found in 'ts-lib-test' (module has no exports)
我是不是把事情搞得太复杂了?我把这个给ChatGPT看了,它说它应该能工作,根据我能找到的每一个相关的SO帖子,这也是真的...我不应该用 typescript 来做这个吗?我应该创建react库吗?如果可能的话,我想为我的组件定义属性类型。我都快把头发扯掉了...

m1m5dgzv

m1m5dgzv1#

你输入和输出都是错误的。
1.使用默认导出时,只需使用

import SomeComponent from 'ts-lib-test';

字符串
1.当你想使用命名的导出时,你需要用这种方式导出它

export {SomeComponent};

相关问题