Giter VIP home page Giter VIP logo

craco-alias's People

Contributors

dependabot[bot] avatar lwoydziak avatar wontem avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

craco-alias's Issues

Module not found: Can't resolve '@alias' in...

Looks like I'm unable to use aliases at all.

comes up with an error:

Module not found: Can't resolve '@alias' in...

package,json

{
  "name": "zoomdashboard",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@craco/craco": "^5.6.4",
    "@material-ui/core": "^4.9.12",
    "babel-eslint": "^10.1.0",
    "bootstrap": "^4.4.1",
    "jquery": "^3.4.1",
    "merge": "^1.2.1",
    "oidc-client": "^1.9.0",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-router-bootstrap": "^0.24.4",
    "react-router-dom": "^4.2.2",
    "react-scripts": "^3.4.1",
    "reactstrap": "^6.3.0",
    "rimraf": "^2.6.2",
    "universal-cookie": "^4.0.3"
  },
  "devDependencies": {
    "ajv": "^6.12.2",
    "craco-alias": "^2.1.1",
    "cross-env": "^5.2.1",
    "eslint": "^6.6.0",
    "eslint-config-react-app": "^5.2.1",
    "eslint-plugin-flowtype": "^4.7.0",
    "eslint-plugin-import": "^2.20.2",
    "eslint-plugin-jsx-a11y": "^6.2.3",
    "eslint-plugin-react": "^7.19.0",
    "typescript": "^3.8.3"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "scripts": {
    "start": "rimraf ./build && craco start",
    "build": "craco build",
    "test": "cross-env CI=true craco test --env=jsdom",
    "eject": "react-scripts eject",
    "lint": "eslint ./src/"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

craco.config.js

module.exports = {
    plugins: [
        {
            plugin: CracoAlias,
            debug: true,
            options: {
                source: "options",
                baseUrl: "./",
                aliases: {
                    "@alias/*": "./src/components/Common/*"
                }
            }
        }
    ]
};

'Cannot parse tsconfig.extend.json' error

Im following the readme instructions but constantly having error "Cannot parse tsconfig.extend.json"
Option "debug: true" doesn't work, at least I don't see any additional info in the console

Here are my config files:
craco.config.js

module.exports = {
    plugins: [
        {
            plugin: require('craco-alias'),
            options: {
                debug: true,
                source: 'tsconfig',
                tsConfigPath: './tsconfig.extend.json',
                baseUrl: './src'
            }
        }
    ],
    style: {
        postcss: {
            plugins: [require('tailwindcss'), require('autoprefixer')]
        }
    }
}

tsconfig.json

{
"extends": "./tsconfig.extend.json",
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
  },
  "include": [
    "src"
  ]
}

tsconfig.extend.json

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

Having this deps in package.json:

{
  ...
"@craco/craco": "^6.1.0",
"react-scripts": "4.0.1",
"craco-alias": "^2.1.1",
"typescript": "4.1.3"
}

Cannot parse tsconfig.extend.json

Follow these steps:

https://github.com/risenforces/craco-alias#ran-into-a-problem

Then describe your problem and paste the plugin output.

This seems like a completely valid tsconfig.extend.json to me

{
    "compilerOptions": {
      // baseUrl is optional for plugin, but some IDEs require it
      "baseUrl": "src",
      "paths": {
        "@components": ["./src/components"],
        "@entities": ["./src/entities"],
        "@factories": ["./src/factories"],
        "@gifs": ["./src/gifs/v5"],
        "@imgs": ["./src/imgs"],
        "@interfaces": ["./src/interfaces"],
        "@root": ["./src"],
        "@store": ["./src/store"],
        "@utils": ["./src/utils"],
        "@missions": ["./src/missions"],
      }
    }
  }
> craco start

Cannot parse tsconfig.extend.json

Please read plugin documentation: https://github.com/risenforces/craco-alias

Does not support aliasing named imports

The current aliases only support aliasing paths. What if I want to alias named imports.

as a trivial example, say instead of importing
import * from 'some-installed-library/sub-module'
i want to alias it to
import * from 'shortened'

with alias

options: {
  source: "options",
  aliases: {
    "shortened": "some-installed-library/sub-module",
  }
}

$ is not escaped in Jest aliases

tsconfig.extend.json

{
  "compilerOptions": {
    "baseUrl": "./src",
    "paths": {
      "$redux/*": ["redux/*"]
    }
  }
}

Relevant excerpt from craco.config.js

  plugins: [
    {
      plugin: CracoAlias,
      options: {
        baseUrl: "./src",
        tsConfigPath: "./tsconfig.extend.json",
        source: "tsconfig",
        debug:true
      }
    }
  ],

Produced Jest alias, as reported by the craco-alias debug output.

`"^$redux/(.*)$": "E:\\myProject\\src\\redux/$1"`

Issue: the dollar sign in the Jest regex is not escaped. Should be "^\$redux/(.*)$"

Cant find path from alias

Hey

So i followed the migration instructions you gave to migrate from cra-alias to croco-alias. unfortunately i now get the following errors when i try to run craco start using npm start

./src/index.js
Module not found: Can't resolve '@components/App' in '/Users/xxx/Documents/Projects/react/xxx/xxx-ui/src'

jsconfig.json

{
	"compilerOptions": {
		"baseUrl": "src",
		"paths": {
			"@components": ["./components"],
			"@constants": ["./constants"],
			"@context": ["./context"],
			"@features": ["./features"],
			"@hooks": ["./hooks"],
			"@i18n": ["./i18n"],
			"@theme": ["./modules/theme"],
			"@reducers": ["./context/reducers"],
			"@actions": ["./context/actions"],
			"@services": ["./services/api"],
			"@utils": ["./utils"]
		}
	}
}

craco.config.js

const CracoAlias = require('craco-alias')

module.exports = {
  plugins:
  {
    plugin: CracoAlias,
    options: {
      source: 'jsconfig'
    }
  }
}

I have also tried to configure the craco.config.js file in manuale mode useing src: 'options'

Versions

"@craco/craco": "^5.4.0",
"craco-alias": "^1.0.4",

Thanks

按照官方给的案例配置craco-alias以后,项目都启动不了

当我按照案例配置好各个文件的时候,发现项目都启动不了? 另外就是在引用过程中,vscode中也是弹出红色警告,贴出代码
craco.config.js如下:
const CracoLessPlugin = require('craco-less');
const CracoAlias = require("craco-alias");

module.exports = {
plugins: [
{
plugin: CracoLessPlugin,
options: {
lessLoaderOptions: {
lessOptions: {
modifyVars: { '@primary-color': '#1DA57A' },
javascriptEnabled: true,
},
},
},
},
{
plugin: CracoAlias,
options: {
source: "tsconfig",
baseUrl: "./src",
tsConfigPath: "./tsconfig.extend.json"
}
}
]
};
tsconfig.json如下:
{
"extends": "./tsconfig.extend.json",
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react"
},
"include": [
"src"
]
}
tsconfig.extend.json如下:
{
"compilerOptions": {
"baseUrl": "./src",
"paths": {
"@src": ["./"]
}
}
}
此时package.json文件如下:
{
"name": "antd-demo-ts",
"version": "0.1.0",
"private": true,
"dependencies": {
"@craco/craco": "^5.8.0",
"@testing-library/jest-dom": "^5.11.4",
"@testing-library/react": "^11.1.0",
"@testing-library/user-event": "^12.1.10",
"@types/jest": "^26.0.15",
"@types/node": "^12.0.0",
"@types/react": "^16.9.53",
"@types/react-dom": "^16.9.8",
"add": "^2.0.6",
"antd": "^4.8.2",
"craco-alias": "^2.1.1",
"craco-less": "^1.17.0",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-loadable": "^5.5.0",
"react-redux": "^7.2.2",
"react-router-dom": "^5.2.0",
"react-scripts": "4.0.0",
"redux": "^4.0.5",
"typescript": "^4.0.3",
"web-vitals": "^0.2.4",
"yarn": "^1.22.10"
},
"scripts": {
"start": "craco start",
"build": "craco build",
"test": "craco test"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}

出现的问额如下:

craco: *** Cannot find ESLint loader (eslint-loader). ***
/Users/xiaoyang/Documents/allProjects/demos/antd-demo-ts/node_modules/react-scripts/scripts/start.js:19
throw err;
^

TypeError: Cannot add property paths, object is not extensible
at verifyTypeScriptSetup (/Users/xiaoyang/Documents/allProjects/demos/antd-demo-ts/node_modules/react-scripts/scripts/utils/verifyTypeScriptSetup.js:239:43)
at Object. (/Users/xiaoyang/Documents/allProjects/demos/antd-demo-ts/node_modules/react-scripts/scripts/start.js:31:1)

并且我引用如下import Routes from '@src/config/routes';也会报错,请问一下,怎么解决

it doesn't work at all when use with `tsconfig`.

Hi.

I have followed the step to use in README.md

tsconfig.extend.json

{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react",
    "noImplicitAny": true,
    "baseUrl": "src",
    "paths": {
      "@/*": ["./src/*"]
    },
    "experimentalDecorators": true,
    "typeRoots": ["./types"]
  },
  "include": ["src"]
}

tsconfig.json

{
  "extends": "./tsconfig.extend.json",
  "compilerOptions": {}
}

craco.config.js

const CracoLessPlugin = require('craco-less');
const CracoAlias = require('craco-alias');

module.exports = {
  plugins: [
    {
      plugin: CracoAlias,
      options: {
        source: "tsconfig",
        baseUrl: "./src",
        tsConfigPath: "./tsconfig.extend.json"
      }
    },
    {
      plugin: CracoLessPlugin,
      options: {
        lessLoaderOptions: {
          lessOptions: {
            modifyVars: {'@primary-color': '#1DA57A'},
            javascriptEnabled: true,
          },
        },
      },
    },
  ],
};

information of DEBUG

here is the information when debug=true

Initial options:

{
  "debug": true,
  "source": "tsconfig",
  "baseUrl": "./",
  "tsConfigPath": "./tsconfig.extend.json"
}

Normalized options:

{
  "source": "tsconfig",
  "baseUrl": "./",
  "tsConfigPath": "./tsconfig.extend.json",
  "debug": true
}

Aliases:

{
  "@": "/path/to/my/project/src"
}

Webpack Config:

{
  "react-native": "react-native-web",
  "@": "/path/to/my/project/src"

Useage

// it should import from './src/store'
import store from '@/store';

tsconfig.json should be right here. The editor can recognize correctly. But craco doesn't

any helps are welcome. thanks for your all ❤️

compilerOptions.paths must not be set (aliased imports are not supported)

compilerOptions.paths must not be set (aliased imports are not supported)

Output

Initial options:

{
  "source": "tsconfig",
  "tsConfigPath": "./tsconfig.extend.json",
  "baseUrl": "./",
  "debug": true
}

Normalized options:

{
  "source": "tsconfig",
  "baseUrl": "./",
  "tsConfigPath": "./tsconfig.extend.json",
  "debug": true
}

Aliases:

{
  "@src": "/Users/lyhourchhen/Developments/gogym-pos/src",
  "@components": "/Users/lyhourchhen/Developments/gogym-pos/src/components",
  "@services": "/Users/lyhourchhen/Developments/gogym-pos/src/services",
  "@pages": "/Users/lyhourchhen/Developments/gogym-pos/src/pages",
  "@api-generator": "/Users/lyhourchhen/Developments/gogym-pos/src/generators/gogym-gen-api.ts",
  "@uri": "/Users/lyhourchhen/Developments/gogym-pos/src/constants/rest-uri.constant.ts"
}

Webpack Config:

{
  "react-native": "react-native-web",
  "src": "/Users/lyhourchhen/Developments/gogym-pos/src",
  "@src": "/Users/lyhourchhen/Developments/gogym-pos/src",
  "@components": "/Users/lyhourchhen/Developments/gogym-pos/src/components",
  "@services": "/Users/lyhourchhen/Developments/gogym-pos/src/services",
  "@pages": "/Users/lyhourchhen/Developments/gogym-pos/src/pages",
  "@api-generator": "/Users/lyhourchhen/Developments/gogym-pos/src/generators/gogym-gen-api.ts",
  "@uri": "/Users/lyhourchhen/Developments/gogym-pos/src/constants/rest-uri.constant.ts"
}

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

craco.config.js

/* eslint-disable @typescript-eslint/no-var-requires */
const CracoLessPlugin = require("craco-less");
const CracoAlias = require("craco-alias");

module.exports = {
  plugins: [
    {
      plugin: CracoAlias,
      options: {
        source: "tsconfig",
        tsConfigPath: "./tsconfig.extend.json",
        baseUrl: "./",
        debug: true,
      },
    },
    {
      plugin: CracoLessPlugin,
      options: {
        lessLoaderOptions: {
          lessOptions: {
            modifyVars: { "@primary-color": "#62caad" },
            javascriptEnabled: true,
          },
        },
      },
    },
  ],
};

Alias resolution requires duplicate

Hi

I wonder if this is a bug from craco-alias or typescript.

I would like to type @layout to resolve to ./layout. then adding a forward / would continue the path.
e.g.
@layout --> ./layout/index.ts
@layout/main --> ./layout/main.ts

So in tsconfig.json I did

"paths": {
    "@layout": ["./layout"],
}

But it doesn't work in both case. For the above use case to work, I should add kind of a duplicate

"paths": {
    "@layout": ["./layout"],
    "@layout/*": ["./layout/*"],
}

"Could not find a declaration file" when aliasing the package

{
  "compilerOptions": {
    "baseUrl": "./",
    "paths": {
      "@my-react": ["./node_modules/react/"]
    }
  }
}

TS cannot find types declaration file for @my-react, even when @types/react is installed.

{
  "compilerOptions": {
    "baseUrl": "./",
    "paths": {
      "@file-alias": ["./src/file.ts"],
      "@folder-alias/*": ["./src/folder/*", "./src/folder/"],
      "@my-react": ["./node_modules/react/"],
      "@types/@my-react": ["./node_modules/@types/react/"]
    }
  }
}

Types aliasing makes no sense too.

Cannot parse valid tsconfig that includes comments

I'm currently using Craco-Alias v3.0.1.

I had a very simple tsconfig file:

{
  "extends": "mybase.tsconfig.json" , // Not actual filename
  "compilerOptions": {
    "baseUrl": "./",
    "paths": {
        // I actually had a comment in the  file there, because I desire a different path, eventually...
        // and TypeScript supports comments in tsconfig files (JSONC, or JSON with Comments)
        // but Craco-Alias does not   :'(
        "@myscope/*": "./packages/myscope/*"
    }
  }
}

But as you can see from the comment in the file above, Craco-Alias does not support Json with Comments, even though that's technically what tsconfig files are. (As you can see when you do tsc --init—you get a file full of comments with a very basic configuration, and tsc happily consumes it.)

Multiple fall back locations in paths do not get compiled

Hey guys,

I have been trying for a while to solve the problem with paths in tsconfig.paths.json. My compiler looks for files in the first location but not the "fall back location".
Here is my tsconfig.paths.json:

{
  "compilerOptions": {
    "baseUrl": "./src",
    "paths": {
      "*": ["*", "core-components/src/*"]
    }
  }
}

Note: the core components folder is inside the root src.

And my craco.config.js:

const CracoAlias = require('craco-alias');
module.exports = {
   plugins: [
      plugin: CracoAlias,
      options: {
        source: 'tsconfig',
        baseUrl: './src',
        tsConfigPath: 'tsconfig.paths.json',
        debug: true
      },
   ]
}

What I get in the console when I let the debug field true:

Initial options:

{
  "source": "tsconfig",
  "baseUrl": "./src",
  "tsConfigPath": "tsconfig.paths.json",
  "debug": true
}

Normalized options:
{
  "source": "tsconfig",
  "baseUrl": "./src",
  "tsConfigPath": "tsconfig.paths.json",
  "debug": true,
  "unsafeAllowModulesOutsideOfSrc": false
}

Initial aliases:
{
  "*": "<path-to-root-folder>\\src\\*"
}

Aliases:
{
  "*": "<path-to-root-folder>\\src\\*"
}

Webpack Config:
{
  "react-native": "react-native-web",
  "*": "<path-to-root-folder>\\src\\*"
}

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

VSCode does not complain about anything. However, when I run npm start (craco start), I get the error Module not found: Can't resolve 'images/abcde.svg' in <path-to-root-folder>/src/images/abcde.svg.
Note: the abcde.svg file exists in src/core-components but not in the src/images. However, I have specified the "": ["", "core-components/src/*"], I would expect the compiler looks to the src/imagesfirst. If the module/svg file is not there, it looks in thecore-components/src/images`. However, it does not.

From the console log, we can't see the "core-components/src/*" added to the Aliases. According to the TS module-resolution, the path together with its fallback locations should be included.

I want to use paths because I can't export hundreds of images in the root/src/core-components/src/images folder and use them somewhere else or override some of them in the root/src/images. The compiler will first look for matched files in this folder if the images exist.

Error if paths are already absolute

https://github.com/risenforces/craco-alias/blob/12071df5ce0d726adb4adb41162c6cd7e95117bb/plugin/extract-aliases/normalize-aliases.js#L10-L11

path.join doesn't work if there're already absolute paths in the aliases option. Maybe it's better to use path.resolve?

Example debug output:

Initial options:

{
  "source": "options",
  "baseUrl": "./",
  "aliases": {
    "PACKAGE": "/APP_ABSOLUTE_PATH/node_modules/PACKAGE",
  },
  "debug": true,
  "unsafeAllowModulesOutsideOfSrc": false
}

Initial aliases:

{
  "PACKAGE": "/BASE_PATH/APP_ABSOLUTE_PATH/node_modules/PACKAGE",
}

The same here:
https://github.com/risenforces/craco-alias/blob/1b9940df7cc8ffe9ce6f5ef569bb3e34c2c86027/plugin/extract-aliases/index.js#L31

There's no option to use absolute path even in baseUrl

error while trying to run npm start

Hi

After making the changes you suggested in issue/1 i get the following errors...

internal/validators.js:125
    throw new ERR_INVALID_ARG_TYPE(name, 'string', value);
    ^

TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined
    at validateString (internal/validators.js:125:11)
    at Object.basename (path.js:1289:5)
    at checkConfig (/Users/ME/Documents/Projects/react/XXX/xxx-ui/node_modules/craco-alias/plugin/pre-check/check-config.js:9:31)
    at preCheck (/Users/ME/Documents/Projects/react/XXX/xxx-ui/node_modules/craco-alias/plugin/pre-check/index.js:18:5)
    at Object.cracoOptions [as overrideWebpackConfig] (/Users/ME/Documents/Projects/react/XXX/xxx-ui/node_modules/craco-alias/plugin/create-overrider.js:6:3)
    at overrideWebpack (/Users/ME/Documents/Projects/react/XXX/xxx-ui/node_modules/@craco/craco/lib/features/plugins.js:42:40)
    at cracoConfig.plugins.forEach.x (/Users/ME/Documents/Projects/react/XXX/xxx-ui/node_modules/@craco/craco/lib/features/plugins.js:64:29)
    at Array.forEach (<anonymous>)
    at applyWebpackConfigPlugins (/Users/ME/Documents/Projects/react/XXX/xxx-ui/node_modules/@craco/craco/lib/features/plugins.js:63:29)
    at mergeWebpackConfig (/Users/ME/Documents/Projects/react/XXX/xxx-ui/node_modules/@craco/craco/lib/features/webpack/merge-webpack-config.js:67:30)
    at overrideWebpackDev (/Users/ME/Documents/Projects/react/XXX/xxx-ui/node_modules/@craco/craco/lib/features/webpack/override.js:11:36)
    at Object.<anonymous> (/Users/ME/Documents/Projects/react/XXX/xxx-ui/node_modules/@craco/craco/scripts/start.js:19:1)
    at Module._compile (internal/modules/cjs/loader.js:776:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)

Module not found in monorepo

I have monorepo with following structure (using lerna):

  • apps
    |_ api // nodejs
    |_ web // react app
  • shared
    |_ common // common code between react and nodejs
    |_ components // common components between react apps

at the root of monorepo I have tsconfig.paths.json:

{
  "compilerOptions": {
    "baseUrl": "./src",
    "paths": {
      "@shared/common/*": ["./shared/common/src/*"],
      "@shared/components/*": ["./shared/components/src/*"],
      "@api/*": ["./apps/api/src/*"],
      "@web/*": ["./apps/web/src/*"]
    }
  }
}

and apps/web/tsconfig.json:

{
  "extends": "../../tsconfig.paths.json",
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
  },
  "include": [
    "src"
  ]
}

and also apps/web/craco.config.js

const CracoAlias = require('craco-alias');
const path = require('path');

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',
      },
    },
  ],
};

I have an import in apps/web/src/App.tsx:

`import '@web/common/axiosSetup';`

The file axiosSetup is located inside apps/web/src/common/axiosSetup.ts

And when I run I get following error:

@program-studio/web: > @program-studio/[email protected] start
@program-studio/web: > craco start
@program-studio/web: The following changes are being made to your tsconfig.json file:
@program-studio/web:   - compilerOptions.paths must not be set (aliased imports are not supported)
@program-studio/web: [HPM] Proxy created: /  -> 
@program-studio/web: [HPM] Proxy created: /  -> 
@program-studio/web: ℹ 「wds」: Project is running at 
@program-studio/web: ℹ 「wds」: webpack output is served from 
@program-studio/web: ℹ 「wds」: Content not from webpack is served from 
@program-studio/web: ℹ 「wds」: 404s will fallback to /
@program-studio/web: Starting the development server...

@program-studio/web: Failed to compile.
@program-studio/web: ./src/App.tsx
@program-studio/web: Module not found: Can't resolve '@web/common/axiosSetup' in '/Users/edubskiy/Dev/work/program-studio/apps/web/src'

So I am trying to import code inside my app/web/src folder with absolute path using alias

Please tell me what do I do wrong and how do fix import?

CRA appears to disallow tsconfig compilerOptions.paths

It also appears to disallow changing isolatedModules, but that's unrelated. CRA forces certain tsconfig options to be set, even if you change them in tsconfig, cra will override whatever you did (I believe to prevent some issues those settings would cause)

So I will not use aliases, as I'm more interested in using typescript

We could use lerna and create packages, or just npm install a package folder npm install ./packages/my-package where my-package folder contains a package.json file

Cannot parse tsconfig.extend.json

package.json
{
"name": "myapp",
"version": "0.1.0",
"private": true,
"dependencies": {
"@craco/craco": "^5.7.0",
"@testing-library/jest-dom": "^5.11.4",
"@testing-library/react": "^11.1.0",
"@testing-library/user-event": "^12.1.10",
"@types/jest": "^26.0.15",
"@types/node": "^12.0.0",
"@types/react": "^16.9.53",
"@types/react-dom": "^16.9.8",
"craco-alias": "^2.1.1",
"eslint-loader": "^4.0.2",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-scripts": "4.0.0",
"typescript": "^4.0.3",
"web-vitals": "^0.2.4"
},
"scripts": {
"start": "craco start",
"build": "craco build",
"test": "craco test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}

tsconfig.extend.json
{
"compilerOptions": {
"baseUrl": "./src",
"paths": {
"@root": ["./"],
"@root/": ["./"]
}
}
}

tsconfig.json
{
"extends": "./tsconfig.extend.json",
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react"
},
"include": [
"src"
]
}

craco.config.js
const CracoAlias = require("craco-alias");

module.exports = {
plugins: [
{
plugin: CracoAlias,
options: {
source: "tsconfig",
tsConfigPath: "./tsconfig.extend.json",
baseUrl: "./src",
},
},
],
};

WARN:
craco: *** Cannot find ESLint loader (eslint-loader). ***
Cannot parse tsconfig.extend.json

Cannot add property paths, object is not extensible

[debug: true]

PS C:\data\test\todo> npm start

> [email protected] start C:\data\test\todo
> craco start

craco:  *** Cannot find ESLint loader (eslint-loader). ***
Initial options:

{
  "source": "tsconfig",
  "baseUrl": "./src",
  "tsConfigPath": "./tsconfig.extend.json",
  "debug": true
}

Normalized options:

{
  "source": "tsconfig",
  "baseUrl": "./src",
  "tsConfigPath": "./tsconfig.extend.json",
  "debug": true
}

Aliases:

{
  "@root": "C:\\data\\test\\todo\\src"
}

Webpack Config:

{
  "react-native": "react-native-web",
  "@root": "C:\\data\\test\\todo\\src"
}

C:\data\test\todo\node_modules\react-scripts\scripts\start.js:19
  throw err;
  ^

TypeError: Cannot add property paths, object is not extensible
    at verifyTypeScriptSetup (C:\data\test\todo\node_modules\react-scripts\scripts\utils\verifyTypeScriptSetup.js:239:43)
    at Object.<anonymous> (C:\data\test\todo\node_modules\react-scripts\scripts\start.js:31:1)
    at Module._compile (internal/modules/cjs/loader.js:1015:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1035:10)
    at Module.load (internal/modules/cjs/loader.js:879:32)
    at Function.Module._load (internal/modules/cjs/loader.js:724:14)
    at Module.require (internal/modules/cjs/loader.js:903:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at start (C:\data\test\todo\node_modules\@craco\craco\lib\cra.js:202:5)
    at C:\data\test\todo\node_modules\@craco\craco\scripts\start.js:27:5

craco.config.js

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.extend.json",
        debug: true
      }
    }
  ]
};

tsconfig.extend.json

{
  "compilerOptions": {
    "baseUrl": "./src",
    "paths": {
      "@root": ["./"],
      "@root/*": ["./*"]
    }
  }
}

tsconfig.json

{
  "extends": "./tsconfig.extend.json",
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react"
  },
  "include": [
    "src"
  ]
}

What am I missing?

I did this. just

yarn create react-app myapp --template typescript
yarn add @craco/craco
yarn add craco-alias -D

Could not parse tsconfig.extend.json

Follow these steps:

https://github.com/risenforces/craco-alias#ran-into-a-problem

Then describe your problem and paste the plugin output.

This seems list a completely valid tsconfig.extend.json to me

{
    "compilerOptions": {
      // baseUrl is optional for plugin, but some IDEs require it
      "baseUrl": "src",
      "paths": {
        "@components": ["./src/components"],
        "@entities": ["./src/entities"],
        "@factories": ["./src/factories"],
        "@gifs": ["./src/gifs/v5"],
        "@imgs": ["./src/imgs"],
        "@interfaces": ["./src/interfaces"],
        "@root": ["./src"],
        "@store": ["./src/store"],
        "@utils": ["./src/utils"],
        "@missions": ["./src/missions"],
      }
    }
  }
> craco start

Cannot parse tsconfig.extend.json

Please read plugin documentation: https://github.com/risenforces/craco-alias

Support `@*`

This config didn't works, but it should:

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@*": ["./src/*"]
    }
  }
}

TypeError: Cannot add property paths, object is not extensible

I don't understand why issues relating to this were closed. But I am facing the same error.

package.json

{
  "name": "aster-frontend",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@craco/craco": "^5.8.0",
    "@reduxjs/toolkit": "^1.4.0",
    "@testing-library/jest-dom": "^5.11.5",
    "@testing-library/react": "^11.1.2",
    "@testing-library/user-event": "^12.2.2",
    "@theme-ui/color": "^0.3.3",
    "@types/jest": "^26.0.15",
    "@types/node": "^14.14.7",
    "@types/react": "^16.9.56",
    "@types/react-dom": "^16.9.9",
    "@types/react-redux": "^7.1.11",
    "@types/theme-ui": "^0.3.7",
    "@types/yup": "^0.29.9",
    "@visx/text": "^1.1.0",
    "axios": "^0.21.0",
    "formik": "^2.2.5",
    "history": "^5.0.0",
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "react-redux": "^7.2.2",
    "react-router-dom": "^6.0.0-beta.0",
    "react-scripts": "4.0.0",
    "redux": "^4.0.5",
    "theme-ui": "^0.3.3",
    "typescript": "^4.0.5",
    "web-vitals": "^0.2.4",
    "yup": "^0.29.3"
  },
  "scripts": {
    "start": "craco start --verbose",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "@typescript-eslint/eslint-plugin": "^4.7.0",
    "@typescript-eslint/parser": "^4.7.0",
    "craco-alias": "^2.1.1",
    "eslint": "^7.13.0",
    "eslint-config-prettier": "^6.15.0",
    "eslint-plugin-prettier": "^3.1.4",
    "eslint-plugin-react": "^7.21.5",
    "prettier": "^2.1.2"
  }
}

tsconfig.paths.json

{
  "compilerOptions": {
    "baseUrl": "./src",
    "paths": {
      "@": [
        "/"
      ],
      "@slices": [
        "./store/slices/"
      ],
      "@components": [
        "./components"
      ]
    }
  }
}

tsconfig.json

{
  "extends": "./tsconfig.paths.json",
  "compilerOptions": {
    "target": "es6",
    "skipDefaultLibCheck": true,
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react"
  },
  "include": [
    "src"
  ],
  "exclude": [
    "node_modules",
    "./node_modules",
    "./node_modules/*",
    "./node_modules/@types/node/index.d.ts"
  ]
}

craco.config.json

// eslint-disable-next-line @typescript-eslint/no-var-requires
const CracoAlias = require("craco-alias");

module.exports = {
    plugins: [
        {
            plugin: CracoAlias,
            options: {
                source: "tsconfig",
                baseUrl: "./",
                tsConfigPath: "./tsconfig.paths.json",
                debug: true,
            },
        },
    ],
};

I have followed the instruction to a T, I still get the error from react scripts. Please what am I missing?

 $ craco start --verbose
craco:  Project root path resolved to:  /Users/abbasegbeyemi/Programming/Aare Tech/aster-frontend
craco:  Config file path resolved to:  /Users/abbasegbeyemi/Programming/Aare Tech/aster-frontend/craco.config.js
craco:  Override started with arguments:  [
  '/Users/abbasegbeyemi/.asdf/installs/nodejs/14.8.0/bin/node',
  '/Users/abbasegbeyemi/Programming/Aare Tech/aster-frontend/node_modules/@craco/craco/scripts/start.js',
  '--verbose'
]
craco:  For environment:  development
craco:  Found craco config file at:  /Users/abbasegbeyemi/Programming/Aare Tech/aster-frontend/craco.config.js
craco:  Overrided craco config with plugin.
craco:  Applied craco config plugins.
craco:  Found Webpack dev config at:  /Users/abbasegbeyemi/Programming/Aare Tech/aster-frontend/node_modules/react-scripts/config/webpack.config.js
craco:  *** Cannot find ESLint loader (eslint-loader). ***
craco:  Overrided PostCSS loader.
craco:  Overrided PostCSS loader.
craco:  Overrided PostCSS loader.
craco:  Overrided PostCSS loader.
Initial options:

{
  "source": "tsconfig",
  "baseUrl": "./",
  "tsConfigPath": "./tsconfig.paths.json",
  "debug": true
}

Normalized options:

{
  "source": "tsconfig",
  "baseUrl": "./",
  "tsConfigPath": "./tsconfig.paths.json",
  "debug": true
}

Aliases:

{
  "@": "/Users/abbasegbeyemi/Programming/Aare Tech/aster-frontend/",
  "@slices": "/Users/abbasegbeyemi/Programming/Aare Tech/aster-frontend/store/slices",
  "@components": "/Users/abbasegbeyemi/Programming/Aare Tech/aster-frontend/components"
}

Webpack Config:

{
  "react-native": "react-native-web",
  "@": "/Users/abbasegbeyemi/Programming/Aare Tech/aster-frontend/",
  "@slices": "/Users/abbasegbeyemi/Programming/Aare Tech/aster-frontend/store/slices",
  "@components": "/Users/abbasegbeyemi/Programming/Aare Tech/aster-frontend/components"
}

craco:  Applied webpack config plugins.
craco:  Overrided require cache for module: /Users/abbasegbeyemi/Programming/Aare Tech/aster-frontend/node_modules/react-scripts/config/webpack.config.js
craco:  Overrided Webpack dev config.
craco:  Found dev server config at:  /Users/abbasegbeyemi/Programming/Aare Tech/aster-frontend/node_modules/react-scripts/config/webpackDevServer.config.js
craco:  Overrided require cache for module: /Users/abbasegbeyemi/Programming/Aare Tech/aster-frontend/node_modules/react-scripts/config/webpackDevServer.config.js
craco:  Overrided dev server config provider.
craco:  Starting CRA at:  /Users/abbasegbeyemi/Programming/Aare Tech/aster-frontend/node_modules/react-scripts/scripts/start.js
/Users/abbasegbeyemi/Programming/Aare Tech/aster-frontend/node_modules/react-scripts/scripts/start.js:19
  throw err;
  ^

TypeError: Cannot add property paths, object is not extensible
    at verifyTypeScriptSetup (/Users/abbasegbeyemi/Programming/Aare Tech/aster-frontend/node_modules/react-scripts/scripts/utils/verifyTypeScriptSetup.js:239:43)
    at Object.<anonymous> (/Users/abbasegbeyemi/Programming/Aare Tech/aster-frontend/node_modules/react-scripts/scripts/start.js:31:1)
    at Module._compile (internal/modules/cjs/loader.js:1251:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1272:10)
    at Module.load (internal/modules/cjs/loader.js:1100:32)
    at Function.Module._load (internal/modules/cjs/loader.js:962:14)
    at Module.require (internal/modules/cjs/loader.js:1140:19)
    at require (internal/modules/cjs/helpers.js:75:18)
    at start (/Users/abbasegbeyemi/Programming/Aare Tech/aster-frontend/node_modules/@craco/craco/lib/cra.js:202:5)
    at /Users/abbasegbeyemi/Programming/Aare Tech/aster-frontend/node_modules/@craco/craco/scripts/start.js:27:5
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Process finished with exit code 1

Does not work with TypeScript on CRA4

Repro here (Yarn PNP):

https://github.com/SnowflakePowered/hydrogen-paper/tree/8be317e82d668528945e6aa7ce37eb223b9928c4/theme

yarn run craco start results in the error

TypeScript error in D:/coding/hydrogen-paper/theme/src/components/ConfigurationWidgets/BooleanWidget/BooleanWidget.tsx(5,6):
Cannot find module 'components/ConfigurationWidgets/ConfigurationWidget/ConfigurationWidget' or its corresponding type declarations.  TS2307

    3 |
    4 | import ConfigurationWidget, { WidgetChildrenProps }
  > 5 | from 'components/ConfigurationWidgets/ConfigurationWidget/ConfigurationWidget'
      |      ^
    6 | import { ConfigurationOption } from 'support/Snowflake'
    7 |
    8 | type BooleanWidgetProps = {

However it seems to work with yarn storybook.

Debug output:

Initial options:

{
  "baseUrl": "./",
  "source": "tsconfig",
  "tsConfigPath": "./tsconfig.paths.json",
  "debug": true
}

Normalized options:

{
  "source": "tsconfig",
  "baseUrl": "./",
  "tsConfigPath": "./tsconfig.paths.json",
  "debug": true,
  "unsafeAllowModulesOutsideOfSrc": false
}

Initial aliases:

{
  "*": "D:\\coding\\hydrogen-paper\\theme\\src",
  "@": "D:\\coding\\hydrogen-paper\\theme\\src",
  "components": "D:\\coding\\hydrogen-paper\\theme\\src\\components",
  "containers": "D:\\coding\\hydrogen-paper\\theme\\src\\containers",
  "support": "D:\\coding\\hydrogen-paper\\theme\\src\\support",
  "stories": "D:\\coding\\hydrogen-paper\\theme\\src\\stories"
}

Aliases:

{
  "*": "D:\\coding\\hydrogen-paper\\theme\\src",
  "@": "D:\\coding\\hydrogen-paper\\theme\\src",
  "components": "D:\\coding\\hydrogen-paper\\theme\\src\\components",
  "containers": "D:\\coding\\hydrogen-paper\\theme\\src\\containers",
  "support": "D:\\coding\\hydrogen-paper\\theme\\src\\support",
  "stories": "D:\\coding\\hydrogen-paper\\theme\\src\\stories"
}

Webpack Config:

{
  "react-native": "react-native-web",
  "*": "D:\\coding\\hydrogen-paper\\theme\\src",
  "@": "D:\\coding\\hydrogen-paper\\theme\\src",
  "components": "D:\\coding\\hydrogen-paper\\theme\\src\\components",
  "containers": "D:\\coding\\hydrogen-paper\\theme\\src\\containers",
  "support": "D:\\coding\\hydrogen-paper\\theme\\src\\support",
  "stories": "D:\\coding\\hydrogen-paper\\theme\\src\\stories"
}

Then describe your problem and paste the plugin output.

compilerOptions.paths must not be set (aliased imports are not supported)

Here's my setup:

// tsconfig.json
{
	"extends": "./tsconfig.paths.json",
	"compilerOptions": {
		"target": "es5",
		"lib": [
			"dom",
			"dom.iterable",
			"esnext"
		],
		"allowJs": true,
		"skipLibCheck": true,
		"esModuleInterop": true,
		"allowSyntheticDefaultImports": true,
		"strict": true,
		"forceConsistentCasingInFileNames": true,
		"noFallthroughCasesInSwitch": true,
		"module": "esnext",
		"moduleResolution": "node",
		"resolveJsonModule": true,
		"isolatedModules": true,
		"noEmit": true,
		"jsx": "react-jsx"
	},
	"include": [
		"src"
	]
}

Then, I created a tsconfig.paths.json:

// tsconfig.paths.json
{
	"compilerOptions": {
		"baseUrl": "./src",
		"paths": {
			"@components/*": ["components/*"]
		}
	}
}

Finally, my craco config:

// craco.config.js
module.exports = {
	style: {
		postcss: {
			plugins: [
				{
					plugin: require('craco-alias'),
					source: "tsconfig",
					baseUrl: "./src",
					tsConfigPath: "./tsconfig.paths.json",
					debug: true,
				},
				require('tailwindcss'),
				require('autoprefixer'),
			],
		},
	},
}

And yet:

-> yarn build
yarn run v1.22.10
$ craco build
The following changes are being made to your tsconfig.json file:
  - compilerOptions.paths must not be set (aliased imports are not supported)

Creating an optimized production build...
Failed to compile.

./src/index.tsx
Cannot find module: '@components/App'. Make sure this package is installed.

You can install this package by running: yarn add @components/App.


error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Why?

Module not found: You attempted to import FILEPATH which falls outside of the project src/ directory. Relative imports outside of src/ are not supported.

Description

Getting an error when I try to import files outside of the project src.

Module not found: You attempted to import /my-app/shared/src/utils which falls outside of the project src/ directory. Relative imports outside of src/ are not supported.

Scenario

I've created a new create-react-app and am using craco.
I'm working in a mono-repo style repository that looks like this:

root
    backend
        src
    shared
        src
    web
        src

Is there a way around this?

TypeError: aliases[aliasName].replace is not a function

In my CRA app I receive:

> craco start

(node:15302) UnhandledPromiseRejectionWarning: TypeError: aliases[aliasName].replace is not a function
    at normalizeAliases (/home/jastako/workspace/servibou/ui/node_modules/craco-alias/plugin/extract-aliases/normalize-aliases.js:8:43)
    at extractAliases (/home/jastako/workspace/servibou/ui/node_modules/craco-alias/plugin/extract-aliases/index.js:46:12)
    at Object.overrideWebpackConfig (/home/jastako/workspace/servibou/ui/node_modules/craco-alias/plugin/create-overrider.js:11:26)
    at overrideWebpack (/home/jastako/workspace/servibou/ui/node_modules/@craco/craco/lib/features/plugins.js:42:40)
    at /home/jastako/workspace/servibou/ui/node_modules/@craco/craco/lib/features/plugins.js:64:29
    at Array.forEach (<anonymous>)
    at applyWebpackConfigPlugins (/home/jastako/workspace/servibou/ui/node_modules/@craco/craco/lib/features/plugins.js:63:29)
    at mergeWebpackConfig (/home/jastako/workspace/servibou/ui/node_modules/@craco/craco/lib/features/webpack/merge-webpack-config.js:110:30)
    at overrideWebpackDev (/home/jastako/workspace/servibou/ui/node_modules/@craco/craco/lib/features/webpack/override.js:11:36)
    at /home/jastako/workspace/servibou/ui/node_modules/@craco/craco/scripts/start.js:27:5
(Use `node --trace-warnings ...` to show where the warning was created)
(node:15302) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:15302) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Terminal will be reused by tasks, press any key to close it.

craco.config.js:

module.exports = {
  plugins: [
    {
      plugin: require("craco-alias"),
      options: {
        source: "options",
        baseUrl: "./src",
        aliases: {
          "@graphql/*": ["graphql/*"],
          "@utils": ["utils"],
          "@utils/*": ["utils/*"],
        },
        debug: true,
      },
    },
  ],
  style: {
    postcss: {
      plugins: [require("tailwindcss"), require("autoprefixer")],
    },
  },
};

Path alias cannot resolve tsx files

I have a path alias defined in my root directory as follows:

# tsconfig.paths.json
{
  "compilerOptions": {
    "baseUrl": "./",
    "paths": {
      "@app/*": ["src/*", "src/"]
    }
  }
}

However the compiler can't resolve .tsx files when using this alias. For e.g.

// src/components/folder/Component1.ts
import Component1 from '@app/components/folder/Component1'; // works fine

// src/components/folder/Component2.tsx
import Component2 from '@app/components/folder/Component2'; // can't resolve
Module not found: Can't resolve '@app/components/folder/Component2' in '/home/juzerzarif/Documents/test-project/src/components/navigation'

Here's my config files:

# tsconfig.json

{
  "extends": "./tsconfig.paths.json",
  "compileOnSave": true,
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react"
  },
  "include": [
    "src"
  ]
}
// craco.config.js

const CracoAlias = require("craco-alias");

module.exports = {
  plugin: [
    {
      plugin: CracoAlias,
      options: {
        source: "tsconfig",
        baseUrl: "./",
        tsConfigPath: "./tsconfig.paths.json"
      }
    }
  ]
}

Cannot find module 'react' or its corresponding type declarations.

Hi.

Faced with the problem starting the project:

Failed to compile.

/home/SOMEPATH/cra+craco/frontend/shared/src/Hello/index.tsx
TypeScript error in /home/SOMEPATH/cra+craco/frontend/shared/src/Hello/index.tsx(1,38):
Cannot find module 'react' or its corresponding type declarations.  TS2307

  > 1 | import React, { FC, useEffect } from 'react'
      |                                      ^
    2 | import icon from './icon.svg'
    3 | 
    4 |

The repo to reproduce the problem: https://github.com/ReshaSD/cra-craco. Use yarn start from the cra+craco/frontend/app-web/ folder

The idea was to use shared components that are not in the src folder:

Folder structure
cra+craco
  - frontend
    - app-web
      - src
          - App.tsx // with `import { Hello } from '@shared'`
          - index.ts
      - package.json // <- scripts: { start: 'craco start'
    - shared
      - src
          - Hello
              - index.tsx // not used in this example
              - index.web.tsx // Hello component
      - index.ts // export * from './src/Hello
      - // no package.json, no tsconfig.json, ....

So I used unsafeAllowModulesOutsideOfSrc option. The error You attempted to import /home/SOMEPATH/cra+craco/frontend/shared which falls outside of the project was gone but anyway I got new error about react module.

Not sure if this issue should be addressed to this repo ... but maybe you know what is going on.

P.S. Run with debug=true
/usr/bin/node /usr/lib/node_modules/npm/bin/npm-cli.js run start --scripts-prepend-node-path=auto

> [email protected] start /home/SOMEPATH/cra+craco/frontend/app-web
> craco start

Initial options:

{
  "source": "tsconfig",
  "baseUrl": "./src",
  "tsConfigPath": "./tsconfig.extends.json",
  "unsafeAllowModulesOutsideOfSrc": true,
  "debug": true
}

Normalized options:

{
  "source": "tsconfig",
  "baseUrl": "./src",
  "tsConfigPath": "./tsconfig.extends.json",
  "debug": true,
  "unsafeAllowModulesOutsideOfSrc": true
}

Initial aliases:

{
  "@shared": "/home/SOMEPATH/cra+craco/frontend/shared"
}

Aliases:

{
  "@shared": "/home/SOMEPATH/cra+craco/frontend/shared"
}

Webpack Config:

{
  "react-native": "react-native-web",
  "@shared": "/home/SOMEPATH/cra+craco/frontend/shared"
}

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


Process finished with exit code 0

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.