47
loading...
This website collects cookies to deliver better user experience
Before we start, "/" really matters when setting paths, TypeScript compiler will viciously throw errors on your face so if yours complains, see if there are any mistakes made on the forward slash or try to give some tweaks with "/" and "."
npx create-react-app myApp --template typescript
// tsconfig.path.json (in root)
{
"compilerOptions": {
"baseUrl": "./src",
"paths": {
"@pages": ["pages"], // this doesn't work for @pages/smth
"@pages/*": ["pages/*"],
"@components": ["components"],
"@components/*": ["components/*"],
...
}
}
"@*": ["*"]
in "paths"
is going to work, but I prefer not to use it because of readability.// tsconfig.json
{
"extends": "./tsconfig.path.json",
"compilerOptions": {
...
}
}
@path
means.You can write all what's in tsconfig.path.json
in tsconfig.json
, but I prefer to separate it because the part is used for a different(or unique per se) functionality.
# npm
$ npm install @craco/craco
$ npm install --dev ts-jest
# yarn
$ yarn add @craco/craco
$ yarn add --dev ts-jest
// craco.config.js (in root)
const path = require('path');
const { pathsToModuleNameMapper } = require('ts-jest');
const { compilerOptions } = require('./tsconfig.path.json');
module.exports = {
webpack: {
alias: {
'@components': path.resolve(__dirname, 'src/components'),
'@pages': path.resolve(__dirname, 'src/pages'),
...
}
},
jest: {
configure: {
preset: 'ts-jest',
moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths, {
prefix: '<rootDir>/src/',
}),
},
},
};
moduleNameMapper
in jest.configure
. You can find it by following the ts-jest
link below.{
...,
"cracoConfig": "craco.config.js"
}
{
...
"scripts": {
"start": "craco start",
"build": "craco build",
"test": "craco test",
"eject": "react-scripts eject",
...
}
}