首页 > 解决方案 > 如何在 React js 中导出组件以在另一个项目中使用?

问题描述

hello world我在react js这个里面做了一个简单的组件

import React from 'react';

function App() {
  return (
    <div >
      hello4
    </div>
  );
}

export default App;

我像这样导出索引文件

import App from './App'
module.exports = {
    App
}

现在我导出这个组件是index.js为了在另一个项目中使用

所以在另一个项目中,我将上面的项目用作这样的依赖项

"dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.5.0",
    "@testing-library/user-event": "^7.2.1",
    "pubnsi": "git+https://git@github.com/naveennsit/pubs.git",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-scripts": "3.4.1"
  },

但是当我在另一个像这样的项目中使用这个组件时,它给了我语法错误

import React from 'react';
import './App.css';
import App from "pubnsi/src/App";
function App1() {
  return (
    <div className="App">
   hello
      <App/>
    </div>
  );
}

export default App1;

我试图在代码沙箱中复制这个错误

https://codesandbox.io/s/nifty-glitter-bj6sz?file=/package.json

但在代码沙箱中没有出错。

包.json 文件

{
  "name": "consukmer",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.5.0",
    "@testing-library/user-event": "^7.2.1",
    "pubnsi": "git+https://git@github.com/naveennsit/pubs.git",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-scripts": "3.4.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

标签: javascriptreactjs

解决方案


要将 Github 存储库用作依赖项,您必须像这样添加它:

"pubnsi": "naveennsit/pubs"

而不是这样:

"pubnsi": "git+https://git@github.com/naveennsit/pubs.git",

推荐阅读