create-react-app Typescript 3.5, Path Alias
The alias solution for craco or rewired create-react-app is react-app-alias for systems as: craco, react-app-rewired, customize-cra
According docs of mentioned systems replace react-scripts
in package.json
and configure next:
react-app-rewired
// config-overrides.js
const {aliasWebpack, aliasJest} = require('react-app-alias')
const options = {} // default is empty for most cases
module.exports = aliasWebpack(options)
module.exports.jest = aliasJest(options)
craco
// craco.config.js
const {CracoAliasPlugin} = require('react-app-alias')
module.exports = {
plugins: [
{
plugin: CracoAliasPlugin,
options: {}
}
]
}
all
Configure aliases in json like this:
// tsconfig.paths.json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"example/*": ["example/src/*"],
"@library/*": ["library/src/*"]
}
}
}
And add this file in extends
section of main typescript config file:
// tsconfig.json
{
"extends": "./tsconfig.paths.json",
// ...
}
Edit - 20/3/20 - Above answer has a solution with a plugin.
Had the same problem. At the time of posting it is currently not supported as is.
This feature is still in development with the CRA team: https://github.com/facebook/create-react-app/pull/6116
If you edit the tsconfig CRA removes changes: https://github.com/facebook/create-react-app/issues/6269
There are some hacks in this thread: https://github.com/facebook/create-react-app/issues/5118 to get aliases working however require customization to the CRA setup which isn't suitable for my use case (using CRA as is).
In my case ,i solved this issue using craco and craco-alias
Install craco and craco-alias
npm install @craco/craco --save
andnpm i -D craco-alias
Create
tsconfig.paths.json
in root directory{ "compilerOptions": { "baseUrl": "./src", "paths": { "@components/*" : ["./components/*"] } } }
Extend
tsconfig.paths.json
intsconfig.json
{ "extends": "./tsconfig.paths.json", //default configs... }
Create
craco.config.js
in root direcoryconst CracoAlias = require("craco-alias"); module.exports = { plugins: [ { plugin: CracoAlias, options: { source: "tsconfig", // baseUrl SHOULD be specified // plugin does not take it from tsconfig baseUrl: "./src", /* tsConfigPath should point to the file where "baseUrl" and "paths" are specified*/ tsConfigPath: "./tsconfig.paths.json" } } ] };
in
package.json
swap"start": "react-scripts start"
with"start": "craco start"