如何告诉 npm 在用户安装包时忽略安装反应

How to tell npm to ignore installing react when user installs package

我正在捆绑一个typescript react组件包,我想知道是否有一种方法可以在用户安装react组件包时忽略react和react-dom。

如果我不从节点模块中删除 react 和 react dom,用户将遇到此问题

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

如果我从节点模块中删除了 react 和 react dom,组件将正常工作。我不想一直来回删除节点模块。我怎样才能简化这个?

如何告诉 package.json 忽略来自节点模块的反应和反应 dom?

tsconfig.json

{
  "compilerOptions": {
    "outDir": "dist",
    "sourceMap": true,
    "noImplicitAny": true,
    "esModuleInterop": true,
    "module": "esnext",
    "target": "es6",
    "moduleResolution": "node",
    "jsx": "react"
  },
  "exclude": ["examples"]
}

package.json

{
  "name": "commentbox-simple-demo",
  "version": "1.0.0",
  "description": "",
  "main": "dist/index.js",
  "scripts": {
    "start": "webpack-dev-server --mode development",
    "transpile": "tsc",
    "prepublishOnly": "npm run transpile"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.11.6",
    "@babel/preset-env": "^7.11.5",
    "@babel/preset-react": "^7.10.4",
    "@types/react": "16.9.23",
    "@types/react-dom": "16.9.5",
    "awesome-ts-loader": "^1.3.1",
    "babel-core": "^6.26.3",
    "babel-preset-env": "^1.7.0",
    "babel-preset-react": "^6.24.1",
    "css-loader": "^4.3.0",
    "html-webpack-plugin": "^4.4.1",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "style-loader": "^1.2.1",
    "ts-loader": "6.2.1",
    "typescript": "3.8.3",
    "webpack": "^4.44.1",
    "webpack-cli": "^3.3.12",
    "webpack-dev-server": "^3.11.0"
  },
  "peerDependencies": {
    "react": "^16.3.0",
    "react-dom": "^16.3.0"
  },
  "dependencies": {
    "@material-ui/core": "^4.11.0",
    "@material-ui/icons": "^4.9.1",
    "@material-ui/types": "^5.1.0"
  }
}

webpack.config.js

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const htmlWebpackPlugin = new HtmlWebpackPlugin({
  template: path.join(__dirname, "examples/index.html"),
  filename: "./index.html",
});
module.exports = {
  entry: path.join(__dirname, "examples/index.tsx"),
  output: {
    path: path.join(__dirname, "dist"),
    filename: "index.js",
  },
  module: {
    rules: [
      {
        test: /\.(ts|tsx|js|jsx)$/,
        use: "ts-loader",
        exclude: /node_modules/,
      },
      {
        test: /\.css$/,
        use: ["style-loader", "css-loader"],
      },
    ],
  },
  plugins: [htmlWebpackPlugin],
  resolve: {
    extensions: [".js", ".jsx", ".ts", ".tsx"],
  },
  devServer: {
    port: 3001,
  },
};

你基本上已经告诉 npm 通过将 react 和 react-dom 放在 peerDependencies 下来做到这一点。这告诉 npm 不要为你的包安装 react 和 react-dom,而是假设你的包正在使用的项目已经有 react 和 react-dom 作为依赖项。

尝试将 react 和 react-dom 添加到 webpack 配置的 externals 属性 中。这告诉 webpack 不要将它们与您的组件一起打包,它应该减少版本冲突。