How to create an example for a react library

后端 未结 1 1303
一生所求
一生所求 2021-01-28 18:04

In the root folder I have an index.js file with some React hooks and context. Some of the content looks like this:

import React, {
  createContext,
  useContext,         


        
1条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-28 18:29

    Because my homebrew-redux has only one file I did the following:

    Provide react as a peer dependency in my root project (homebrew-redux) and to build my homebrew-redux I added babel, then a script to build it, here are the relevant parts of root package.json:

    {
      "name": "homebrew-redux",
      "main": "./index.js",
      "scripts": {
        "build": "./node_modules/.bin/babel store/index.js --out-file index.js"
      },
      "eslintConfig": {
        "extends": "react-app"
      },
      "peerDependencies": {
        "react": "^16.8.6"
      },
      "devDependencies": {
        "@babel/cli": "^7.6.2",
        "@babel/core": "^7.6.2",
        "@babel/preset-env": "^7.6.2",
        "@babel/preset-react": "^7.0.0"
      }
    }
    

    To be able to build homebrew-redux I added .babelrc to the root with the following content:

    {
      "presets": ["@babel/preset-react", "@babel/preset-env"]
    }
    

    If your project has multiple files you may have to install react-scripts and create a production build (not sure because i didn't test it). Make sure output goes to index.js in the project root because that's the entry point in the root package.json (value for main). If you can't build to that file then you can change the main value in the root package.json

    In the root delete node_modules and yarn.lock and re run yarn install.

    Build homebrew-redux with yarn build that will create an index.js in the root directory. This file does not contain react in it's output because it's a peer dependency.

    In the example directory I added homebrew-redux as a local dependency to the example/package.json

    "dependencies": {
      "react": "^16.8.6",
      "react-dom": "^16.8.6",
      "react-scripts": "3.0.1",
      "reselect": "^4.0.0",
      "homebrew-redux": "file:../"
    },
    

    In example remove node_modules and yarn.lock and re run yarn install.

    Now I can import homebrew-redux from the example like so:

    import {
      compose,
      createStore,
      createStoreProvider,
      applyMiddleware,
    } from 'homebrew-redux';
    

    Ran yarn start and everything works.

    0 讨论(0)
提交回复
热议问题