簡體   English   中英

從本地導入 React 組件 npm package 返回空 object

[英]Import React component from local npm package return empty object

我正在構建我的第一個 npm package 的反應組件。

在我使用 webpack 成功構建后,我嘗試使用npm link對其進行測試。

它已連接,但組件未加載。 它給了我一堆這樣的錯誤

未捕獲的錯誤:元素類型無效:需要字符串(對於內置組件)或類/函數(對於復合組件),但得到:object。 您可能忘記從定義組件的文件中導出組件,或者您可能混淆了默認導入和命名導入。 檢查 `App` 的渲染方法。

所以我試圖console.log()組件。 它返回一個空的Object

我為此苦苦掙扎了 2 天,不知道出了什么問題。

這是一些配置

webpack.config.js

var path = require("path");
const isDevelopment = process.env.NODE_ENV === 'development'
const MiniCssExtractPlugin = require('mini-css-extract-plugin')

module.exports = {
    mode: "production",
    entry: {
        index: path.join(__dirname, 'src', 'index.tsx')
    },
    plugins: [
        new MiniCssExtractPlugin({
            filename: isDevelopment ? '[name].css' : '[name].[hash].css',
            chunkFilename: isDevelopment ? '[id].css' : '[id].[hash].css'
        })
    ],
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                loader: 'ts-loader',
                exclude: /node_modules/,
                options: { allowTsInNodeModules: true }
            },
            {
                test: /\.css$/i,
                use: ["style-loader", "css-loader"],
            },
            {
                test: /\.module\.s[ac]ss$/,
                use: [
                    isDevelopment ? 'style-loader': MiniCssExtractPlugin.loader,
                    {
                        loader: 'css-loader',
                        options: {
                            modules: true,
                            sourceMap: isDevelopment
                        }
                    },
                    {
                        loader: 'sass-loader',
                        options: {
                            sourceMap: isDevelopment
                        }
                    }
                ]
            },
            {
                test: /\.s[ac]ss$/i,
                exclude: /\.module.(s[ac]ss)$/,
                use: [
                    // Creates `style` nodes from JS strings
                    isDevelopment ? 'style-loader': MiniCssExtractPlugin.loader,
                    // to generate a .d.ts module
                    "css-modules-typescript-loader",
                    // Translates CSS into CommonJS
                    {loader: "css-loader", options: {modules: true}},
                    // Compiles Sass to CSS
                    {loader: "sass-loader", options: {sourceMap: isDevelopment}},
                ],
            },
        ]
    },
    resolve: {
        extensions: [".ts", ".tsx", ".js", ".css", ".scss"]
    },
    output: {
        filename: '[name].js',
        path: path.resolve(__dirname, 'dist'),
    },
}

tsconfig.json

{
  "compilerOptions": {
    "outDir": "./dist/",
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "declaration": true,
    "declarationMap": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "removeComments": true,
    "noImplicitAny": true,
    "noEmit": false,
    "jsx": "react-jsx",
    "sourceMap": true,
    "plugins": [{"name": "typescript-plugin-css-modules"}]
  },
  "include": [
    "src"
  ]
}

package.json

{
  "name": "react-dissolve",
  "version": "1.0.0",
  "description": "A color and image animated dissolve effect.",
  "main": "./dist/index.js",
  "types": "./dist/index.d.ts",
  "files": [
    "dist",
    "src"
  ],
  "scripts": {
    "build": "webpack"
  },
  "author": "jack szeto",
  "license": "MIT",
  "devDependencies": {
    "@babel/core": "^7.16.5",
    "@babel/preset-env": "^7.16.5",
    "@babel/preset-react": "^7.16.5",
    "@testing-library/jest-dom": "^5.16.1",
    "@testing-library/react": "^12.1.2",
    "@testing-library/user-event": "^13.5.0",
    "@types/color-string": "^1.5.2",
    "@types/jest": "^27.0.3",
    "@types/node": "^16.11.15",
    "@types/node-sass": "^4.11.2",
    "@types/react": "^17.0.37",
    "@types/react-dom": "^17.0.11",
    "color-string": "^1.9.0",
    "css-loader": "^6.5.1",
    "css-modules-typescript-loader": "^4.0.1",
    "mini-css-extract-plugin": "^2.4.5",
    "node-sass": "^7.0.1",
    "rc-slider": "^9.7.5",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-p5": "^1.3.24",
    "react-scripts": "5.0.0",
    "sass": "^1.45.1",
    "sass-loader": "^12.4.0",
    "simplex-noise": "^3.0.0",
    "style-loader": "^3.3.1",
    "ts-loader": "^9.2.6",
    "typescript": "^4.5.4",
    "web-vitals": "^2.1.2",
    "webpack": "^5.65.0",
    "webpack-cli": "^4.9.1"
  },
  "peerDependencies": {
    "react": "^17.0.2",
    "react-p5": "^1.3.24",
    "simplex-noise": "^3.0.0",
    "color-string": "^1.9.0",
    "rc-slider": "^9.7.5",
    "sass": "^1.45.1"
  },
  "dependencies": {}
}

構建被放在dist文件夾中,它似乎在 dist 中完美成功構建。

截屏:

在此處輸入圖像描述

最小復制案例:

通過使用上面相同的配置。 我創建了一個測試項目(見下面的結構)。

我運行npm run build以使用webpack構建組件。

然后npm link將測試項目鏈接到一個新的 ts React 項目。 試圖導入,但它產生了同樣的錯誤。

用例

import Test from 'npm-test';
...
<Test />

文件結構

npm-test/
  dist/
  node_modules/
  src/
    declarations.d.ts
    index.tsx
    style.module.scss
  .babelrc
  .gitgnore
  .npmignore
  package.json
  tsconfig.json
  webpack.config.js

索引.tsx

import React, { CSSProperties } from 'react'
import styles from './style.module.scss';

interface TestProps {
    className?: string,
    style?: CSSProperties,
}
const Test = ({className, style}:TestProps) => {
    return (
        <div className={`${styles.test} ${className}`}
            style={{...style}}
        >
            Test
        </div>
    )
}
export default Test;

導出的 index.d.ts

import { CSSProperties } from 'react';
interface TestProps {
    className?: string;
    style?: CSSProperties;
}
declare const Test: ({ className, style }: TestProps) => JSX.Element;
export default Test;
//# sourceMappingURL=index.d.ts.map

感謝您閱讀長文!

我已經解決了這個問題。 感謝@JaredSmith 幫助我。

我搞砸了webpack但最后,我決定繼續使用更易於使用的匯總

找到Portexe 的 Rollup 教程,非常有幫助。

所以我把文件結構改成了這個

npm-test-hellow-world/
  src/
    component/
      hello-world.tsx
    index.ts
  .babelrc
  .gitgnore
  .npmignore
  package.json
  tsconfig.json
  rollup.config.js

由於在hello-world.tsx中 function 組件默認導出

declare const HelloWorld: React.FC<HelloWorldProps>;
export default HelloWorld;

不知何故,編譯器沒有導出組件。 所以我把它放在src/component/文件夾中並從src/index.ts

export {default} from './component/hello-world';
// notice: 
// export * from './component/hello-world';
// didn't work

它有效。 不太清楚為什么,如果有人能解釋一下。 我會很感激的。

如果您想查看更多詳細信息,可以查看GitHub 存儲庫

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM