Issue
So, I'm using this tsconfig.json:
{
"compilerOptions": {
"baseUrl": ".",
"declaration": true,
"module": "ES6",
"moduleResolution": "node",
"outDir": "./lib/",
"paths": {
"@src/*": ["src/*"]
},
"preserveConstEnums": true,
"removeComments": true,
"sourceMap": true,
"target": "ES6"
},
"include": [
"global.d.ts",
"src/**/*.ts"
]
}
Where you can see the alias @src is defined for my code.
tsc/webpack have no problem building everything but while editing in VS Code, I can't get rid of this error message when I import something as
import { xxx } from '@src/xxx';
Anyone with the same problem? For me, it's weird to see this because if it's compiling/building properly (from tsc and webpack), it means the configuration is correct. So why VS Code is displaying this error msg? It's just annoying but I wanna solve it.
tsconfig.json file is also using the standard name (no custom -p option for tsc) so, VS Code should be able to read it automatically, right? Or any extra configuration is needed for the IDE?
Solution
After long time (I forgot about the question already...) I made it work (don't know if even was possible when the original question was posted).
I'll write here what I did, in case it can help other people :)
Basically, I needed the following:
1. Define paths in tsconfig.json
This was in the original question, but including it here too for completion:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@src": ["src"],
"@src/*": ["src/*"],
}
}
2. Install tsconfig-paths
npm i -D tsconfig-paths
If you are using webpack add tsconfig-paths-webpack-plugin too and add the plugin in your webpack.config.js like this:
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
module.exports = {
// ...
resolve: {
extensions: ['.ts', '.tsx', '.js', '.json'],
plugins: [new TsconfigPathsPlugin({ configFile: 'tsconfig.json' })],
},
};
If you are using NextJS the configuration for the plugin goes like this in next.config.js:
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
module.exports = {
webpack: (config) => {
config.resolve.plugins.push(
new TsconfigPathsPlugin({ configFile: 'tsconfig.json' })
);
return config;
},
};
I'm not sure if it was just VS Code being improved (therefore my problem was fixed automatically in this one year and a half that passed since I posted the question), but this is what I'm using now and is working fine. Hope it's helpful for others too :)
Note (2022/07/31 with TS 4.6.4) - TsconfigPathsPlugin is still needed if you try to import non-ts code (i.e. an asset) from TS -by using any other loader-.
Example:
import icon from '@assets/icon.svg';
I've found that the webpack plugin is still required to achieve that.
Answered By - danikaze
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.