-->

How to configure react-script so that it doesn'

2020-02-26 18:48发布

问题:

I'm currently using create-react-app to bootstrap one of my projects. Basically, I'm trying to set up paths in tsconfig.json by adding these to the default tsconfig.json generated by create-react-app:

"baseUrl": "./src",
"paths": {
  "interfaces/*": [
    "common/interfaces/*",
  ],
  "components/*": [
    "common/components/*",
  ],
},

However, every time I run yarn start which basically runs react-scripts start, it deletes my changes and generates the default configurations again.

How can I tell create-react-app to use my custom configs?

回答1:

I was able to do this by using advice from this issue.

Put the configuration options react scripts likes to remove in a separate file (e.g. paths.json) and reference it from tsconfig.json via the extends directive.

paths.json:

{
  "compilerOptions": {
  "baseUrl": "./src",
  "paths": {
    "interfaces/*": [ "common/interfaces/*"],
    "components/*": [ "common/components/*"],
    }
  }
}

tsconfig.json

{
  "extends": "./paths.json"
   ...rest of tsconfig.json
}


回答2:

Create React App does not currently support baseUrl. However there is a workaround...to setup baseUrl for both webpack and the IDE you have to do the following:

  1. Create a .env file with the following code:
NODE_PATH=./
  1. Create a tsconfig.paths.json file with the following code inside:
{
  "compilerOptions": {
    "baseUrl": "src",
    "paths": {
      "src/*": ["*"]
    }
  }
}
  1. Add the following line to tsconfig.json
{
  "extends": "./tsconfig.paths.json",
  ...
}


回答3:

You can't and I am unsure when you will be able to. I have been trying to use baseUrl and paths so I can avoid relative imports but as you can see they are intentionally removing certain values. The "(yet)" is encouraging but (sigh) who knows when they will officially be supporting it. I recommend subscribing to this github issue to be alerted if/when this changes.

The following changes are being made to your tsconfig.json file:
      - compilerOptions.baseUrl must not be set (absolute imports are not supported (yet))
      - compilerOptions.paths must not be set (aliased imports are not supported)