NOTE FOR CONFUSING TERMS
// Absolute path: paths which are relative to specific path
import Input from 'components' // src/components
import UsersUtils from 'page/users/utils' // src/page/users/utils
// Alias path: other naming to specific path
import Input from '@components' // src/components
import UsersUtils from '@userUtils' // src/page/users/utils
In order for webpack's aliases to work, you need to configure the default webpack.config.js
of create-react-app
.
The official way is to use the eject
script.
But the recommended way is to use a library without ejecting, like craco
.
After following the installation, add craco.config.js
to your root folder with the desired configuration.
My example:
// craco.config.js
const path = require(`path`);
const alias = require(`./src/config/aliases`);
const SRC = `./src`;
const aliases = alias(SRC);
const resolvedAliases = Object.fromEntries(
Object.entries(aliases).map(([key, value]) => [key, path.resolve(__dirname, value)]),
);
module.exports = {
webpack: {
alias: resolvedAliases,
},
};
Where aliases.js
(./src/config/aliases
) exports a helper function:
const aliases = (prefix = `src`) => ({
'@atoms': `${prefix}/components/atoms`,
'@molecules': `${prefix}/components/molecules`,
'@organisms': `${prefix}/components/organisms`,
'@templates': `${prefix}/components/templates`,
'@components': `${prefix}/components`,
'@config': `${prefix}/config`,
'@enums': `${prefix}/enums`,
'@hooks': `${prefix}/hooks`,
'@icons': `${prefix}/components/atoms/Icons`,
'@styles': `${prefix}/styles`,
'@utils': `${prefix}/utils`,
'@state': `${prefix}/state`,
'@types': `${prefix}/types`,
'@storybookHelpers': `../.storybook/helpers`,
});
module.exports = aliases;
VSCode IntelliSense
In addition, you should add jsconfig.json
file for path IntelliSense in VSCode (or tsconfig.json
), see followup question.
Now such code with IntelliSense will work:
// NOTE THAT THOSE ARE ALIASES, NOT ABSOLUTE PATHS
// AutoComplete and redirection works
import {ColorBox} from '@atoms';
import {RECOIL_STATE} from '@state';