UNPKG

2 kBJavaScriptView Raw
1const { existsSync } = require("fs");
2const path = require("path");
3const { appSrc, appPath, appTsConfig, appJsConfig, appNodeModules } = require("./paths");
4const resolve = require("resolve");
5
6function getAdditionalModulePaths(options = {}) {
7 const baseUrl = options.baseUrl;
8 const baseUrlResolved = path.resolve(appPath, baseUrl);
9
10 if (baseUrl == null) {
11 const nodePath = process.env.NODE_PATH || "";
12 return nodePath.split(path.delimiter).filter(Boolean);
13 }
14
15 if (path.relative(appNodeModules, baseUrlResolved) === "") return null;
16 if (path.relative(appSrc, baseUrlResolved) === "") return [appSrc];
17 if (path.relative(appPath, baseUrlResolved) === "") return null;
18
19 throw new Error(
20 chalk.red.bold(
21 "Your project's `baseUrl` can only be set to `src` or `node_modules`." +
22 " Create React App does not support other values at this time."
23 )
24 );
25}
26
27function getJestAliases(options = {}) {
28 const baseUrl = options.baseUrl;
29 const baseUrlResolved = path.resolve(appPath, baseUrl);
30
31 if (!baseUrl) return {};
32
33 if (path.relative(appPath, baseUrlResolved) === "") {
34 return {
35 "src/(.*)$": "<rootDir>/src/$1"
36 };
37 }
38}
39
40function getModules() {
41 const hasTsConfig = existsSync(appTsConfig);
42 const hasJsConfig = existsSync(appJsConfig);
43
44 if (hasTsConfig && hasJsConfig) {
45 throw new Error(
46 "You have both a tsconfig.json and a jsconfig.json. If you are using TypeScript please remove your jsconfig.json file."
47 );
48 }
49
50 let config;
51
52 if (hasTsConfig) {
53 const ts = require(resolve.sync("typescript", {
54 basedir: appNodeModules
55 }));
56 config = ts.readConfigFile(appTsConfig, ts.sys.readFile).config;
57 } else if (hasJsConfig) {
58 config = require(appJsConfig);
59 }
60
61 config = config || {};
62 const options = config.compilerOptions || {};
63
64 return {
65 additionalModulePaths: getAdditionalModulePaths(options),
66 jestAliases: getJestAliases(options),
67 hasTsConfig
68 };
69}
70
71module.exports = getModules();