Get version number from package.json in React Redux (create-react-app)

后端 未结 4 1222
悲哀的现实
悲哀的现实 2021-02-01 11:34

OP EDIT: If anyone else comes across this: the app was created using create-react-app, which limits importing to within the src folder. However if you upgrade react-scri

相关标签:
4条回答
  • 2021-02-01 12:09

    From your edit I would suggest to try

    import packageJson from '/package.json';
    

    You could also try to create a symlink:

    # From the project root.
    cd src; ln -s ../package.json package.alias.json
    

    List contents of src directory and you'll see the symlink.

    ls
    #=> package.alias.json -> ../package.json
    

    Adding the .alias helps reduce the magic for others and your future self when looking at this. Plus, it'll help text editors keep them apart. You'll thank me later. Just make sure you update your JS code to import from ./package.alias.json instead of ./package.json.

    Also take a look at this question: The create-react-app imports restriction outside of src directory

    0 讨论(0)
  • 2021-02-01 12:19

    I don't think getting version by 'import' or 'require' package is correct. You can add a script in you package.json

    "start": "REACT_APP_VERSION=$npm_package_version react-app-script start",
    

    You can get it by "process.env.REACT_APP_VERSION" in any js files.

    It also works in build scripts, like this:

    "build": "REACT_APP_VERSION=$npm_package_version react-app-script build",
    
    0 讨论(0)
  • 2021-02-01 12:21

    Try this.

    // in package.json
    "version": "1.0.0"
    
    // in index.js
    import packageJson from '../package.json';
    console.log(packageJson.version); // "1.0.0"
    
    0 讨论(0)
  • 2021-02-01 12:25

    Solving this without importing and exposing package.json to the create-react-app

    Requires: version 1.1.0+ of create-react-app

    .env

    REACT_APP_VERSION=$npm_package_version
    REACT_APP_NAME=$npm_package_name
    

    index.js

    console.log(`${process.env.REACT_APP_NAME} ${process.env.REACT_APP_VERSION}`)
    

    Note: the version (and many other npm config params) can be accessed

    Note 2: changes to the .env file will be picked only after you restart the development server

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