25
loading...
This website collects cookies to deliver better user experience
create-react-app
cli, you will notice that there isn't a webpack config to mess with unless you eject it running npm run eject
, which will expose the entire configuration and makes you responsible of maintaining it. I prefer not ejecting my react application because I prefer the ease of use using react-scripts, so there must be another way.npm i @craco/craco
craco.config.js
in the root of the project and add the following contentconst path = require('path');
module.exports = {
webpack: {
alias: { '@': path.resolve(__dirname, './src') },
},
};
src/
folder in the root of the project containing all the components I use in a components/
subfolder. Other folders are helpers under helpers/
or custom hooks hooks/
. The alias I am setting up will point to the src/
folder. So whenever I write import Component from '@/components/myComponent'
it will resolve to 'src/components/myComponent'
, independent of the path I am currently work in. craco
instead of react-scripts
in our package.json
scripts section:{
"scripts": {
"start": "craco start",
"build": "craco build",
"test": "craco test"
}
}
eslint-plugin-import
to keep import order clean and tidy.settings
key.settings: {
'import/resolver': {
alias: {
map: [['@', './src']],
extensions: ['.ts', '.tsx', '.js', '.jsx', '.json'],
}
},
},
alias
key here will tell ESLint about the alias key we've setup in our webpack config through craco. I also want to import the extensions listed above without typing out the extension, so that's what that part is for.extends
key:extends: [
'plugin:react/recommended',
'plugin:import/recommended',
'plugin:import/typescript'],
rules: {
'import/order': [
'error',
{
pathGroups: [
{
pattern: '@/**',
group: 'parent',
position: 'before',
},
],
},
],
},
pattern
key should be treated the same way as parent imports. Adding that last key position
with value 'before'
will move them over relative parent imports. You can read about what those keys do in the official docs of eslint-plugin-importtsconfig.json
and add the following:{
"compilerOptions": {
"paths": { "@/*": ["./src/*"] },
}
}
@/*
to my src/
folder.