I'm maintaining an electron app using Typescript. I'm trying to implement absolute paths for imports in my project.
I understand that the way you would normally resolve this would be to edit webpack config, but since I'm using react CRA, and ideally don't want to "eject" and manage things myself just for this issue, I've been looking for other ways to solve the problem.
The intent is to go from something like this:
import * as Constants for '../../../../types/Constants'
to:
import * as Constants from '@types/Constants'
After reading through lots of articles, these are the steps I "think" I should be taking:
So far what I've done is:
- Installed 'react-app-rewired' via NPM, and set up the config-overrides.js (to allow absolute imports to work).
- Updated the tsconfig.json file (to allow VSCode to "see" the absolute imports) (EDIT: Most of the steps I've tried come from absolute path with react, react-app-rewire and typescript)
//~config-overrides.js
module.exports = function override(config, env) {
config.resolve = {
...config.resolve,
alias: {
...config.resolve.alias,
'@types': path.resolve(__dirname, 'src/types')
}
}
return config;
Doing a console.log() of the config shows the alias field was set correctly. This allows the system to be aware of the imports via their absolute paths. Importing via the @types path operates as expected and I'm able to build, launch, and interact with my app without issue.
The problem arises with VSCode Intellisense, which marks all the absolute imports with the "red squiggly" and thus blocking things like autocomplete and being able to navigate to function/field definitions. I tried to resolve this by updating my tsconfig.json file thusly (specifcally adding the "extends" option and the referenced "tsconfig.paths.json" file):
// ~tsconfig.json
{
"extends": "./tsconfig.paths.json",
"compilerOptions": {
"target": "ES2015",
"module": "esnext",
"allowJs": true,
"sourceMap": true,
"outDir": "./build",
"strict": true,
"noImplicitAny": false,
"esModuleInterop": true,
"preserveSymlinks": true,
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"skipLibCheck": true,
"allowSyntheticDefaultImports": true,
"forceConsistentCasingInFileNames": true,
"moduleResolution": "node",
"isolatedModules": true,
"noEmit": true,
"resolveJsonModule": true,
"jsx": "preserve"
},
"include": [
"src/backend/**/*.ts",
"src/backend/**/*.tsx",
"src/backend/**/*.js",
"src/electron.ts"
]
}
// ~tsconfig.paths.json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@types/*": ["./src/types/*"]
}
}
}
Possible issue: When I build, I receive the following two error messages, and I don't know what to do with them:
- compilerOptions.baseUrl must not be set (absolute imports are not supported (yet))
- compilerOptions.paths must not be set (aliased imports are not supported)
EDIT: I have a TSLint file in my project. Do I need to make any updates to that to make this work?