Reputation: 31
===== 2021/03/17 Update =====
If anyone still have the same issue. You can try this:
webpack.config.js
module.exports = {
...
resolve: {
alias: {
components: path.resolve(process.cwd(), './src/components'),
},
},
};
tsconfig.json
{
...
"baseUrl": ".",
"path": {
"components/*": ["./src/components/*"]
}
}
===== Origin Post =====
I have a Alert React component below:
import React from 'react';
interface Props {
message: string;
};
const Alert = (props: Props) => {
return (
<div>{props.message}</div>
);
};
export default Alert;
I use the alias import instead of relative import:
// alias import
import Alert from 'components/Alert';
// relative import
// import Alert from '../../components/Alert';
const App = () => {
return (
<div>
<Alert message="I want to know the interface of Alert" />
</div>
);
};
export default App;
If I type "<Alert me" in relative import, VSCode will show the auto-complete options.
However, when I use the alias import, VSCode won't show the auto-complete.
Is there any possible way to let the VSCode knows the 'components/Alert' is '../../components/Alert', and show me the auto-complete that I can understand the interface of Alert's props?
Here is how I setting the alias, I had been tried both webpack config and tsconfig:
webpack.config.js
...
resolve: {
modules: ['node_modules', 'src'],
extensions: ['.ts', '.tsx', '.js', '.jsx'],
mainFields: ['browser', 'jsnext:main', 'main'],
alias: {
'components/*': path.resolve(process.cwd(), 'src/components/*'),
'containers/*': path.resolve(process.cwd(), 'src/containers/*'),
'images/*': path.resolve(process.cwd(), 'src/images/*'),
'hooks/*': path.resolve(process.cwd(), 'src/hooks/*'),
},
}
tsconfig.json
"compilerOptions": {
...
"baseUrl": "src",
"paths": {
"components": ["components"],
"containers": ["containers"],
"images": ["images"],
"hooks": ["hooks"]
}
},
"include": ["src/**/*.ts", "src/**/*.tsx"],
"exclude": ["node_modules"]
folder structure:
- src
- components
- Alert
- index.tsx
- containers
- App
- index.tsx
Upvotes: 3
Views: 3191
Reputation: 229
You will have to set the baseUrl
option as relative to the paths you are aliasing, so if you have alias path set to ./src/components
then the baseUrl
of that path is ./
.
Here is an example:
"baseUrl": "./",
"paths": {
"@components/*": [
"./src/components/*"
],
or
"baseUrl": "./src",
"paths": {
"@components/*": [
"components/*"
],
Upvotes: 2