@@ -15,7 +15,7 @@ const chalk = require('react-dev-utils/chalk');
1515const resolve = require ( 'resolve' ) ;
1616
1717/**
18- * Get the baseUrl of a compilerOptions object.
18+ * Get additional module paths based on the baseUrl of a compilerOptions object.
1919 *
2020 * @param {Object } options
2121 */
@@ -46,6 +46,15 @@ function getAdditionalModulePaths(options = {}) {
4646 return [ paths . appSrc ] ;
4747 }
4848
49+ // If the path is equal to the root directory we ignore it here.
50+ // We don't want to allow importing from the root directly as source files are
51+ // not transpiled outside of `src`. We do allow importing them with the
52+ // absolute path (e.g. `src/Components/Button.js`) but we set that up with
53+ // an alias.
54+ if ( path . relative ( paths . appPath , baseUrlResolved ) === '' ) {
55+ return null ;
56+ }
57+
4958 // Otherwise, throw an error.
5059 throw new Error (
5160 chalk . red . bold (
@@ -55,6 +64,48 @@ function getAdditionalModulePaths(options = {}) {
5564 ) ;
5665}
5766
67+ /**
68+ * Get webpack aliases based on the baseUrl of a compilerOptions object.
69+ *
70+ * @param {* } options
71+ */
72+ function getWebpackAliases ( options = { } ) {
73+ const baseUrl = options . baseUrl ;
74+
75+ if ( ! baseUrl ) {
76+ return { } ;
77+ }
78+
79+ const baseUrlResolved = path . resolve ( paths . appPath , baseUrl ) ;
80+
81+ if ( path . relative ( paths . appPath , baseUrlResolved ) === '' ) {
82+ return {
83+ src : paths . appSrc ,
84+ } ;
85+ }
86+ }
87+
88+ /**
89+ * Get jest aliases based on the baseUrl of a compilerOptions object.
90+ *
91+ * @param {* } options
92+ */
93+ function getJestAliases ( options = { } ) {
94+ const baseUrl = options . baseUrl ;
95+
96+ if ( ! baseUrl ) {
97+ return { } ;
98+ }
99+
100+ const baseUrlResolved = path . resolve ( paths . appPath , baseUrl ) ;
101+
102+ if ( path . relative ( paths . appPath , baseUrlResolved ) === '' ) {
103+ return {
104+ 'src/(.*)$' : '<rootDir>/src/$1' ,
105+ } ;
106+ }
107+ }
108+
58109function getModules ( ) {
59110 // Check if TypeScript is setup
60111 const hasTsConfig = fs . existsSync ( paths . appTsConfig ) ;
@@ -89,6 +140,8 @@ function getModules() {
89140
90141 return {
91142 additionalModulePaths : additionalModulePaths ,
143+ webpackAliases : getWebpackAliases ( options ) ,
144+ jestAliases : getJestAliases ( options ) ,
92145 hasTsConfig,
93146 } ;
94147}
0 commit comments