I am trying to setup Path alias in my project by adding these values to tsconfig.json:
"compilerOptions": { "baseUrl": "src", "paths": { "@store/*": ["store/*"] },
And if I create an import, neither IntelliJ or VSCode bother me:
import { AppState } from '@store/index';
But when I compile the application I get this warning:
The following changes are being made to your tsconfig.json file: - compilerOptions.paths must not be set (aliased imports are not supported)
And it bombs saying it cannot find the reference:
TypeScript error in C:/xyz.tsx(2,26): Cannot find module '/store'. TS2307
Is there any workaround or it is not supported by create-react-app --typescript
?
In my case ,i solved this issue using craco and craco-alias
Install craco and craco-alias npm install @craco/craco --save
and npm i -D craco-alias
Create tsconfig.paths.json
in root directory
{ "compilerOptions": { "baseUrl": "./src", "paths": { "@components/*" : ["./components/*"] } } }
Extend tsconfig.paths.json
in tsconfig.json
{ "extends": "./tsconfig.paths.json", //default configs... }
Create craco.config.js
in root direcory
const 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"
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:
// 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.config.js const {CracoAliasPlugin} = require('react-app-alias') module.exports = { plugins: [ { plugin: CracoAliasPlugin, options: {} } ] }
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", // ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With