@apollion-dsi/scripts 0.7.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. package/.prettierignore +6 -0
  2. package/.prettierrc.js +1 -0
  3. package/CHANGELOG.md +8 -0
  4. package/README.MD +91 -0
  5. package/audit-ci.json +5 -0
  6. package/eslint.config.js +33 -0
  7. package/lib/bin.d.ts +2 -0
  8. package/lib/bin.js +34 -0
  9. package/lib/bin.js.map +1 -0
  10. package/lib/command/build.d.ts +3 -0
  11. package/lib/command/build.js +145 -0
  12. package/lib/command/build.js.map +1 -0
  13. package/lib/command/create/helper.d.ts +7 -0
  14. package/lib/command/create/helper.js +98 -0
  15. package/lib/command/create/helper.js.map +1 -0
  16. package/lib/command/create/index.d.ts +1 -0
  17. package/lib/command/create/index.js +149 -0
  18. package/lib/command/create/index.js.map +1 -0
  19. package/lib/command/dev.d.ts +3 -0
  20. package/lib/command/dev.js +85 -0
  21. package/lib/command/dev.js.map +1 -0
  22. package/lib/command/test.d.ts +1 -0
  23. package/lib/command/test.js +32 -0
  24. package/lib/command/test.js.map +1 -0
  25. package/lib/config/env.d.ts +15 -0
  26. package/lib/config/env.js +78 -0
  27. package/lib/config/env.js.map +1 -0
  28. package/lib/config/modules.d.ts +15 -0
  29. package/lib/config/modules.js +92 -0
  30. package/lib/config/modules.js.map +1 -0
  31. package/lib/config/paths.d.ts +22 -0
  32. package/lib/config/paths.js +61 -0
  33. package/lib/config/paths.js.map +1 -0
  34. package/lib/config/shared.d.ts +24 -0
  35. package/lib/config/shared.js +14 -0
  36. package/lib/config/shared.js.map +1 -0
  37. package/lib/config/webpack.config.d.ts +187 -0
  38. package/lib/config/webpack.config.js +300 -0
  39. package/lib/config/webpack.config.js.map +1 -0
  40. package/lib/config/webpackDevServer.config.d.ts +34 -0
  41. package/lib/config/webpackDevServer.config.js +67 -0
  42. package/lib/config/webpackDevServer.config.js.map +1 -0
  43. package/lib/index.d.ts +3 -0
  44. package/lib/index.js +10 -0
  45. package/lib/index.js.map +1 -0
  46. package/lib/utils/FileSizeReporter.d.ts +12 -0
  47. package/lib/utils/FileSizeReporter.js +151 -0
  48. package/lib/utils/FileSizeReporter.js.map +1 -0
  49. package/lib/utils/InlineChunkHtmlPlugin.d.ts +8 -0
  50. package/lib/utils/InlineChunkHtmlPlugin.js +54 -0
  51. package/lib/utils/InlineChunkHtmlPlugin.js.map +1 -0
  52. package/lib/utils/InterpolateHtmlPlugin.d.ts +7 -0
  53. package/lib/utils/InterpolateHtmlPlugin.js +21 -0
  54. package/lib/utils/InterpolateHtmlPlugin.js.map +1 -0
  55. package/lib/utils/ModuleNotFoundPlugin.d.ts +5 -0
  56. package/lib/utils/ModuleNotFoundPlugin.js +11 -0
  57. package/lib/utils/ModuleNotFoundPlugin.js.map +1 -0
  58. package/lib/utils/ModuleScopePlugin.d.ts +5 -0
  59. package/lib/utils/ModuleScopePlugin.js +11 -0
  60. package/lib/utils/ModuleScopePlugin.js.map +1 -0
  61. package/lib/utils/WebpackDevServerUtils.d.ts +22 -0
  62. package/lib/utils/WebpackDevServerUtils.js +154 -0
  63. package/lib/utils/WebpackDevServerUtils.js.map +1 -0
  64. package/lib/utils/checkRequiredFiles.d.ts +1 -0
  65. package/lib/utils/checkRequiredFiles.js +28 -0
  66. package/lib/utils/checkRequiredFiles.js.map +1 -0
  67. package/lib/utils/devServerMiddleware.d.ts +8 -0
  68. package/lib/utils/devServerMiddleware.js +19 -0
  69. package/lib/utils/devServerMiddleware.js.map +1 -0
  70. package/lib/utils/formatWebpackMessages.d.ts +5 -0
  71. package/lib/utils/formatWebpackMessages.js +32 -0
  72. package/lib/utils/formatWebpackMessages.js.map +1 -0
  73. package/lib/utils/getPublicUrlOrPath.d.ts +1 -0
  74. package/lib/utils/getPublicUrlOrPath.js +39 -0
  75. package/lib/utils/getPublicUrlOrPath.js.map +1 -0
  76. package/lib/utils/printBuildError.d.ts +1 -0
  77. package/lib/utils/printBuildError.js +14 -0
  78. package/lib/utils/printBuildError.js.map +1 -0
  79. package/lib/utils/printHostingInstructions.d.ts +1 -0
  80. package/lib/utils/printHostingInstructions.js +12 -0
  81. package/lib/utils/printHostingInstructions.js.map +1 -0
  82. package/package.json +81 -0
  83. package/scripts/validate.sh +16 -0
  84. package/src/bin.ts +41 -0
  85. package/src/command/build.ts +188 -0
  86. package/src/command/create/helper.ts +97 -0
  87. package/src/command/create/index.ts +200 -0
  88. package/src/command/dev.ts +95 -0
  89. package/src/command/test.ts +33 -0
  90. package/src/config/env.ts +82 -0
  91. package/src/config/modules.ts +115 -0
  92. package/src/config/paths.ts +88 -0
  93. package/src/config/shared.ts +27 -0
  94. package/src/config/webpack.config.js +308 -0
  95. package/src/config/webpackDevServer.config.ts +78 -0
  96. package/src/index.ts +3 -0
  97. package/src/utils/FileSizeReporter.ts +168 -0
  98. package/src/utils/InlineChunkHtmlPlugin.js +67 -0
  99. package/src/utils/InterpolateHtmlPlugin.js +27 -0
  100. package/src/utils/ModuleNotFoundPlugin.js +13 -0
  101. package/src/utils/ModuleScopePlugin.js +13 -0
  102. package/src/utils/WebpackDevServerUtils.ts +179 -0
  103. package/src/utils/checkRequiredFiles.ts +22 -0
  104. package/src/utils/devServerMiddleware.ts +20 -0
  105. package/src/utils/formatWebpackMessages.ts +30 -0
  106. package/src/utils/getPublicUrlOrPath.ts +39 -0
  107. package/src/utils/printBuildError.ts +8 -0
  108. package/src/utils/printHostingInstructions.ts +12 -0
  109. package/template/.editorconfig +43 -0
  110. package/template/.prettierignore +6 -0
  111. package/template/.prettierrc.js +1 -0
  112. package/template/audit-ci.json +5 -0
  113. package/template/commitlint.config.js +1 -0
  114. package/template/eslint.config.js +3 -0
  115. package/template/jest.config.js +4 -0
  116. package/template/public/index.html +20 -0
  117. package/template/src/App.test.tsx +10 -0
  118. package/template/src/App.tsx +35 -0
  119. package/template/src/index.tsx +10 -0
  120. package/template/tsconfig.json +25 -0
  121. package/tsconfig.json +18 -0
@@ -0,0 +1,200 @@
1
+ import os from 'os';
2
+ import path from 'path';
3
+
4
+ import chalk from 'chalk';
5
+ import spawn from 'cross-spawn';
6
+ import fs from 'fs-extra';
7
+
8
+ import {
9
+ projectNameInput,
10
+ shouldUseYarn,
11
+ templateDependencies,
12
+ templateFolder,
13
+ tryGitCommit,
14
+ tryGitInit,
15
+ validProjectName,
16
+ } from './helper';
17
+
18
+ export async function createTemplate(projectName: string) {
19
+ return getProjectName({ projectName })
20
+ .then(createProjectFolder)
21
+ .then(copyTemplate)
22
+ .then(createPackageJson)
23
+ .then(changeCurrentDirectory)
24
+ .then(installDependencies)
25
+ .then(startGitRepo)
26
+ .then(successMessage);
27
+ }
28
+
29
+ async function getProjectName(config) {
30
+ const { projectName } = config;
31
+
32
+ const [result, reason] = validProjectName(projectName);
33
+
34
+ const isValidName = result && !!projectName;
35
+
36
+ if (!isValidName) {
37
+ if (projectName) {
38
+ console.error(chalk.red(`Nome Invalido: ${reason}`));
39
+ }
40
+
41
+ const { inputName } = await projectNameInput();
42
+
43
+ config.projectName = inputName;
44
+ }
45
+
46
+ return config;
47
+ }
48
+
49
+ async function createProjectFolder(config) {
50
+ const projectFolder = path.resolve(config.projectName);
51
+
52
+ await fs.ensureDir(projectFolder);
53
+
54
+ config.projectFolder = projectFolder;
55
+
56
+ return config;
57
+ }
58
+
59
+ async function copyTemplate(config) {
60
+ const { projectFolder } = config;
61
+
62
+ await fs.copy(templateFolder, projectFolder);
63
+
64
+ console.log(chalk.green(`Criando novo projeto em:\n${chalk.cyan(projectFolder)}\n`));
65
+
66
+ return config;
67
+ }
68
+
69
+ async function createPackageJson(config) {
70
+ const { projectName, projectFolder } = config;
71
+
72
+ await fs.writeJson(
73
+ path.join(projectFolder, 'package.json'),
74
+ {
75
+ name: projectName,
76
+ version: '0.1.0',
77
+ private: true,
78
+ author: process.env.USER || os.hostname(),
79
+ license: 'MIT',
80
+ scripts: {
81
+ start: 'scripts dev',
82
+ build: 'scripts build',
83
+ test: 'scripts test -- --config=jest.config.js',
84
+ lint: 'eslint --quiet src --ext ts,tsx',
85
+ 'lint:full': 'eslint src --ext ts,tsx',
86
+ 'lint:fix': 'eslint --fix src --ext ts,tsx',
87
+ 'prettier:write': 'prettier src/ --write',
88
+ 'audit-dependencies': 'audit-ci --config audit-ci.json',
89
+ },
90
+ husky: {
91
+ hooks: {
92
+ 'pre-commit': 'lint-staged',
93
+ 'commit-msg': 'commitlint -E HUSKY_GIT_PARAMS',
94
+ },
95
+ },
96
+ 'lint-staged': {
97
+ '*.{json,css,md}': ['yarn prettier:write'],
98
+ '*.{ts,tsx}': ['yarn audit-dependencies', 'yarn lint', 'yarn prettier:write'],
99
+ },
100
+ },
101
+ {
102
+ spaces: 2,
103
+ },
104
+ );
105
+
106
+ return config;
107
+ }
108
+
109
+ async function changeCurrentDirectory(config) {
110
+ process.chdir(config.projectFolder);
111
+
112
+ return config;
113
+ }
114
+
115
+ async function installDependencies(config) {
116
+ const useYarn = shouldUseYarn();
117
+
118
+ const displayCommand = useYarn ? 'yarn' : 'npm';
119
+
120
+ console.log(`Instalando dependencias com ${chalk.yellow(useYarn ? 'yarn' : 'npm')}\n`);
121
+
122
+ config.useYarn = useYarn;
123
+ config.displayCommand = displayCommand;
124
+
125
+ return new Promise((resolve, reject) => {
126
+ let command = 'npm';
127
+
128
+ let args = ['install', '--save', '--loglevel', 'error'].concat(templateDependencies);
129
+
130
+ if (useYarn) {
131
+ command = 'yarnpkg';
132
+
133
+ args = ['add', '--exact'].concat(templateDependencies);
134
+ }
135
+
136
+ const child = spawn(command, args, { stdio: 'inherit' });
137
+
138
+ child.on('close', (code) => {
139
+ if (code !== 0) {
140
+ reject(new Error(`${command} ${args.join(' ')}`));
141
+ } else {
142
+ resolve(config);
143
+ }
144
+ });
145
+ });
146
+ }
147
+
148
+ async function startGitRepo(config) {
149
+ const success = tryGitInit();
150
+
151
+ config.gitStarted = success;
152
+
153
+ if (success) {
154
+ const { useYarn, projectFolder } = config;
155
+
156
+ const hooks = ['lint-staged', 'husky', '@commitlint/cli', '@commitlint/config-conventional'];
157
+
158
+ let command = 'npm';
159
+
160
+ let args = ['install', '--save', '--loglevel', 'error'].concat(hooks);
161
+
162
+ if (useYarn) {
163
+ command = 'yarnpkg';
164
+
165
+ args = ['add', '--dev', '--exact'].concat(hooks);
166
+ }
167
+
168
+ console.log(`Iniciando Git Hooks\n`);
169
+
170
+ return new Promise((resolve, reject) => {
171
+ const child = spawn(command, args, { stdio: 'inherit' });
172
+
173
+ child.on('close', (code) => {
174
+ if (code !== 0) {
175
+ reject(new Error(`${command} ${args.join(' ')}`));
176
+ } else {
177
+ config.gitInitialCommit = tryGitCommit(projectFolder);
178
+
179
+ resolve(config);
180
+ }
181
+ });
182
+ });
183
+ }
184
+
185
+ return config;
186
+ }
187
+
188
+ async function successMessage(config) {
189
+ if (config.gitStarted && config.gitInitialCommit) {
190
+ const { projectName, projectFolder, displayCommand, useYarn } = config;
191
+
192
+ console.log();
193
+ console.log(chalk.green(`Sucesso! Projeto ${chalk.white(projectName)} Criado em:\n${chalk.white(projectFolder)}`));
194
+ console.log();
195
+ console.log('Comandos:\n');
196
+ console.log(chalk.cyan(`${displayCommand} start`));
197
+ console.log(chalk.cyan(`${displayCommand} ${useYarn ? '' : 'run '}build`));
198
+ console.log(`\n\n`);
199
+ }
200
+ }
@@ -0,0 +1,95 @@
1
+ process.env.BABEL_ENV = 'development';
2
+ process.env.NODE_ENV = 'development';
3
+
4
+ // Makes the script crash on unhandled rejections instead of silently
5
+ // ignoring them.
6
+ process.on('unhandledRejection', (err) => {
7
+ throw err;
8
+ });
9
+
10
+ import fs from 'fs';
11
+
12
+ import chalk from 'chalk';
13
+ import merge from 'deepmerge';
14
+ import webpack, { Configuration } from 'webpack';
15
+ import WebpackDevServer from 'webpack-dev-server';
16
+
17
+ import { getEnviroment } from '../config/env';
18
+ import defaultPaths, { AppPaths } from '../config/paths';
19
+ import { CustomConfigType, defaultDevConfig } from '../config/shared';
20
+ import configFactory from '../config/webpack.config';
21
+ import createDevServerConfig from '../config/webpackDevServer.config';
22
+ import checkRequiredFiles from '../utils/checkRequiredFiles';
23
+ import { choosePort, createCompiler, prepareProxy, prepareUrls } from '../utils/WebpackDevServerUtils';
24
+
25
+ export async function createDevServer(paths: AppPaths, userConfig: CustomConfigType = defaultDevConfig) {
26
+ const useCustomConfig = fs.existsSync(paths.appCustomConfig);
27
+
28
+ const { configureWebpack, ...customConfig }: CustomConfigType = useCustomConfig
29
+ ? merge.all([defaultDevConfig, userConfig, require(paths.appCustomConfig) ?? {}])
30
+ : Object.assign(defaultDevConfig, userConfig);
31
+
32
+ const { port: devPort, host: devHost, ...devOptions } = customConfig;
33
+ const resolvedHost = devHost || 'localhost';
34
+ const PORT = await choosePort(resolvedHost, devPort ?? 3000);
35
+
36
+ if (PORT == null) {
37
+ return;
38
+ }
39
+
40
+ try {
41
+ if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
42
+ process.exit(1);
43
+ }
44
+
45
+ const baseConfig = configFactory('development', paths, devOptions) as Configuration;
46
+
47
+ const config =
48
+ configureWebpack && typeof configureWebpack === 'function'
49
+ ? configureWebpack(baseConfig, 'development')
50
+ : baseConfig;
51
+
52
+ const tscCompileOnError = process.env.TSC_COMPILE_ON_ERROR === 'true';
53
+ const protocol = process.env.HTTPS === 'true' ? 'https' : 'http';
54
+ const urls = prepareUrls(protocol, resolvedHost, PORT!, paths.publicUrlOrPath.slice(0, -1));
55
+
56
+ const appName = require(paths.appPackageJson).name;
57
+ const compiler = createCompiler({
58
+ appName,
59
+ config,
60
+ urls,
61
+ useYarn: true,
62
+ useTypeScript: true,
63
+ tscCompileOnError,
64
+ webpack,
65
+ });
66
+
67
+ const proxySetting = require(paths.appPackageJson).proxy;
68
+ const proxyConfig = prepareProxy(proxySetting, paths.appPublic, paths.publicUrlOrPath);
69
+ const serverConfig = createDevServerConfig(proxyConfig, urls.lanUrlForConfig, paths);
70
+ const devServer = new WebpackDevServer({ ...serverConfig, host: resolvedHost, port: PORT! }, compiler);
71
+
72
+ await devServer.start();
73
+ if (useCustomConfig) {
74
+ console.log(`${chalk.cyan('Using custom config from:')} ${chalk.yellow(paths.appCustomConfig)}\n`);
75
+ }
76
+ console.log(chalk.cyan('Starting the development server...\n'));
77
+
78
+ (['SIGINT', 'SIGTERM'] as const).forEach((sig) => {
79
+ process.on(sig, async () => {
80
+ await devServer.stop();
81
+ process.exit();
82
+ });
83
+ });
84
+ } catch (err: any) {
85
+ if (err && err.message) {
86
+ console.log(err.message);
87
+ }
88
+ process.exit(1);
89
+ }
90
+ }
91
+
92
+ if (require.main === module) {
93
+ getEnviroment(defaultPaths);
94
+ createDevServer(defaultPaths);
95
+ }
@@ -0,0 +1,33 @@
1
+ process.env.BABEL_ENV = 'test';
2
+ process.env.NODE_ENV = 'test';
3
+ process.env.PUBLIC_URL = '';
4
+
5
+ process.on('unhandledRejection', (err) => {
6
+ throw err;
7
+ });
8
+
9
+ require('../config/env');
10
+
11
+ import { execSync } from 'child_process';
12
+
13
+ import jestRunner from 'jest-cli';
14
+
15
+ const argv = process.argv.slice(2);
16
+
17
+ function isInGitRepository() {
18
+ try {
19
+ execSync('git rev-parse --is-inside-work-tree', { stdio: 'ignore' });
20
+ return true;
21
+ } catch (e) {
22
+ return false;
23
+ }
24
+ }
25
+
26
+ // Watch unless on CI or explicitly running all tests
27
+ if (!process.env.CI && argv.indexOf('--watchAll') === -1 && argv.indexOf('--watchAll=false') === -1) {
28
+ // https://github.com/facebook/create-react-app/issues/5210
29
+ const hasSourceControl = isInGitRepository();
30
+ argv.push(hasSourceControl ? '--watch' : '--watchAll');
31
+ }
32
+
33
+ jestRunner.run(argv);
@@ -0,0 +1,82 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+
4
+ import { CustomConfigType } from './shared';
5
+
6
+ export function getEnviroment(paths) {
7
+ const { NODE_ENV, ENV } = process.env;
8
+
9
+ if (!NODE_ENV) {
10
+ throw new Error('The NODE_ENV environment variable is required but was not specified.');
11
+ }
12
+
13
+ const dotenvFiles = [
14
+ `${paths.dotenv}.${NODE_ENV}.local`,
15
+ `${paths.dotenv}.${ENV}.local`,
16
+ // Don't include `.env.local` for `test` environment
17
+ // since normally you expect tests to produce the same
18
+ // results for everyone
19
+ NODE_ENV !== 'test' && `${paths.dotenv}.local`,
20
+ `${paths.dotenv}.${NODE_ENV}`,
21
+ `${paths.dotenv}.${ENV}`,
22
+ paths.dotenv,
23
+ ].filter(Boolean) as Array<string>;
24
+
25
+ // Load environment variables from .env* files. Suppress warnings using silent
26
+ // if this file is missing. dotenv will never modify any environment variables
27
+ // that have already been set. Variable expansion is supported in .env files.
28
+ dotenvFiles.forEach((dotenvFile) => {
29
+ if (fs.existsSync(dotenvFile)) {
30
+ require('dotenv-expand')(
31
+ require('dotenv').config({
32
+ path: dotenvFile,
33
+ }),
34
+ );
35
+ }
36
+ });
37
+
38
+ const appDirectory = fs.realpathSync(process.cwd());
39
+ process.env.NODE_PATH = (process.env.NODE_PATH || '')
40
+ .split(path.delimiter)
41
+ .filter((folder) => folder && !path.isAbsolute(folder))
42
+ .map((folder) => path.resolve(appDirectory, folder))
43
+ .join(path.delimiter);
44
+ }
45
+
46
+ export default function getClientEnvironment(publicUrl: string, config: CustomConfigType) {
47
+ // Grab NODE_ENV and REACT_APP_* environment variables and prepare them to be
48
+ // injected into the application via DefinePlugin in webpack configuration.
49
+ const REACT_APP = /^REACT_APP_/i;
50
+
51
+ const raw = Object.keys(process.env)
52
+ .filter((key) => REACT_APP.test(key))
53
+ .reduce((env, key) => Object.assign(env, { [key]: process.env[key] }), {
54
+ // Useful for determining whether we’re running in production mode.
55
+ // Most importantly, it switches React into the correct mode.
56
+ NODE_ENV: process.env.NODE_ENV || 'development',
57
+ // Useful for resolving the correct path to static assets in `public`.
58
+ // For example, <img src={process.env.PUBLIC_URL + '/img/logo.png'} />.
59
+ // This should only be used as an escape hatch. Normally you would put
60
+ // images into the `src` and `import` them in code to get their paths.
61
+ PUBLIC_URL: publicUrl,
62
+ // We support configuring the sockjs pathname during development.
63
+ // These settings let a developer run multiple simultaneous projects.
64
+ // They are used as the connection `hostname`, `pathname` and `port`
65
+ // in webpackHotDevClient. They are used as the `sockHost`, `sockPath`
66
+ // and `sockPort` options in webpack-dev-server.
67
+ WDS_SOCKET_HOST: process.env.WDS_SOCKET_HOST,
68
+ WDS_SOCKET_PATH: process.env.WDS_SOCKET_PATH,
69
+ WDS_SOCKET_PORT: process.env.WDS_SOCKET_PORT,
70
+ // Whether or not react-refresh is enabled.
71
+ // react-refresh is not 100% stable at this time,
72
+ // which is why it's disabled by default.
73
+ // It is defined here so it is available in the webpackHotDevClient.
74
+ FAST_REFRESH: !!config.useFastRefresh,
75
+ });
76
+ // Stringify all values so we can feed into webpack DefinePlugin
77
+ const stringified = {
78
+ 'process.env': Object.keys(raw).reduce((env, key) => Object.assign(env, { [key]: JSON.stringify(raw[key]) }), {}),
79
+ };
80
+
81
+ return { raw, stringified };
82
+ }
@@ -0,0 +1,115 @@
1
+ import path from 'path';
2
+
3
+ import chalk from 'chalk';
4
+ import resolve from 'resolve';
5
+
6
+ import paths from './paths';
7
+
8
+ // Check if TypeScript is setup
9
+ const ts = require(
10
+ resolve.sync('typescript', {
11
+ basedir: paths.appNodeModules,
12
+ }),
13
+ );
14
+
15
+ /**
16
+ * Get additional module paths based on the baseUrl of a compilerOptions object.
17
+ *
18
+ * @param {Object} options
19
+ */
20
+ function getAdditionalModulePaths(options: any = {}) {
21
+ const { baseUrl } = options;
22
+
23
+ if (!baseUrl) {
24
+ return '';
25
+ }
26
+
27
+ const baseUrlResolved = path.resolve(paths.appPath, baseUrl);
28
+
29
+ // We don't need to do anything if `baseUrl` is set to `node_modules`. This is
30
+ // the default behavior.
31
+ if (path.relative(paths.appNodeModules, baseUrlResolved) === '') {
32
+ return null;
33
+ }
34
+
35
+ // Allow the user set the `baseUrl` to `appSrc`.
36
+ if (path.relative(paths.appSrc, baseUrlResolved) === '') {
37
+ return [paths.appSrc];
38
+ }
39
+
40
+ // If the path is equal to the root directory we ignore it here.
41
+ // We don't want to allow importing from the root directly as source files are
42
+ // not transpiled outside of `src`. We do allow importing them with the
43
+ // absolute path (e.g. `src/Components/Button.js`) but we set that up with
44
+ // an alias.
45
+ if (path.relative(paths.appPath, baseUrlResolved) === '') {
46
+ return null;
47
+ }
48
+
49
+ // Otherwise, throw an error.
50
+ throw new Error(
51
+ chalk.red.bold(
52
+ "Your project's `baseUrl` can only be set to `src` or `node_modules`." +
53
+ ' Create React App does not support other values at this time.',
54
+ ),
55
+ );
56
+ }
57
+
58
+ /**
59
+ * Get webpack aliases based on the baseUrl of a compilerOptions object.
60
+ *
61
+ * @param {*} options
62
+ */
63
+ function getWebpackAliases(options: any = {}) {
64
+ const { baseUrl } = options;
65
+
66
+ if (!baseUrl) {
67
+ return {};
68
+ }
69
+
70
+ const baseUrlResolved = path.resolve(paths.appPath, baseUrl);
71
+
72
+ if (path.relative(paths.appPath, baseUrlResolved) === '') {
73
+ return {
74
+ src: paths.appSrc,
75
+ };
76
+ }
77
+ }
78
+
79
+ /**
80
+ * Get jest aliases based on the baseUrl of a compilerOptions object.
81
+ *
82
+ * @param {*} options
83
+ */
84
+ function getJestAliases(options: any = {}) {
85
+ const { baseUrl } = options;
86
+
87
+ if (!baseUrl) {
88
+ return {};
89
+ }
90
+
91
+ const baseUrlResolved = path.resolve(paths.appPath, baseUrl);
92
+
93
+ if (path.relative(paths.appPath, baseUrlResolved) === '') {
94
+ return {
95
+ '^src/(.*)$': '<rootDir>/src/$1',
96
+ };
97
+ }
98
+ }
99
+
100
+ function getModules() {
101
+ const config = ts.readConfigFile(paths.appTsConfig, ts.sys.readFile).config || {};
102
+
103
+ const options = config.compilerOptions || {};
104
+
105
+ const additionalModulePaths = getAdditionalModulePaths(options);
106
+
107
+ return {
108
+ additionalModulePaths,
109
+ webpackAliases: getWebpackAliases(options),
110
+ jestAliases: getJestAliases(options),
111
+ hasTsConfig: true,
112
+ };
113
+ }
114
+
115
+ export default getModules();
@@ -0,0 +1,88 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+
4
+ import getPublicUrlOrPath from '../utils/getPublicUrlOrPath';
5
+
6
+ export type AppPaths = {
7
+ dotenv: string;
8
+ appPath: string;
9
+ appBuild: string;
10
+ appPublic: string;
11
+ appHtml: string;
12
+ appIndexJs: string;
13
+ appSrc: string;
14
+ appCustomConfig: string;
15
+ appTsConfig: string;
16
+ yarnLockFile: string;
17
+ testsSetup: string;
18
+ proxySetup: string;
19
+ appNodeModules: string;
20
+ appPackageJson: string;
21
+ publicUrlOrPath: string;
22
+ moduleFileExtensions: string[];
23
+ };
24
+
25
+ export const moduleFileExtensions = [
26
+ 'web.mjs',
27
+ 'mjs',
28
+ 'web.js',
29
+ 'js',
30
+ 'web.ts',
31
+ 'ts',
32
+ 'web.tsx',
33
+ 'tsx',
34
+ 'json',
35
+ 'web.jsx',
36
+ 'jsx',
37
+ ];
38
+
39
+ export function createAppPaths(basePath: string = process.cwd()): AppPaths {
40
+ const appDirectory = fs.realpathSync(basePath);
41
+ const resolveApp = (relativePath) => path.resolve(appDirectory, relativePath);
42
+
43
+ const appPackageJson = resolveApp('package.json');
44
+
45
+ const publicUrlOrPath = getPublicUrlOrPath(
46
+ process.env.NODE_ENV === 'development',
47
+ require(appPackageJson).homepage,
48
+ process.env.PUBLIC_URL,
49
+ );
50
+
51
+ // Resolve file paths in the same order as webpack
52
+ const resolveModule = (resolveFn, filePath) => {
53
+ const extension = moduleFileExtensions.find((ext) => fs.existsSync(resolveFn(`${filePath}.${ext}`)));
54
+
55
+ if (extension) {
56
+ return resolveFn(`${filePath}.${extension}`);
57
+ }
58
+
59
+ return resolveFn(`${filePath}.js`);
60
+ };
61
+
62
+ const appCustomConfig = resolveApp('scriptsrc.js');
63
+ const customConfigExist = fs.existsSync(appCustomConfig);
64
+ const appBuildPathOutput = require(appCustomConfig).output;
65
+
66
+ const appBuildPath = customConfigExist && appBuildPathOutput ? appBuildPathOutput : 'build';
67
+
68
+ return {
69
+ dotenv: resolveApp('.env'),
70
+ appPath: resolveApp('.'),
71
+ appBuild: resolveApp(appBuildPath),
72
+ appPublic: resolveApp('public'),
73
+ appHtml: resolveApp('public/index.html'),
74
+ appIndexJs: resolveModule(resolveApp, 'src/index'),
75
+ appSrc: resolveApp('src'),
76
+ appTsConfig: resolveApp('tsconfig.json'),
77
+ yarnLockFile: resolveApp('yarn.lock'),
78
+ testsSetup: resolveModule(resolveApp, 'src/setupTests'),
79
+ proxySetup: resolveApp('src/setupProxy.js'),
80
+ appNodeModules: resolveApp('node_modules'),
81
+ appCustomConfig,
82
+ appPackageJson,
83
+ publicUrlOrPath,
84
+ moduleFileExtensions,
85
+ };
86
+ }
87
+
88
+ export default createAppPaths();
@@ -0,0 +1,27 @@
1
+ import { Configuration } from 'webpack';
2
+
3
+ export type CustomConfigType = {
4
+ port?: number;
5
+ host?: string;
6
+ head?: HeadConfigType;
7
+ constants?: Record<string, string>;
8
+ i18nConfig?: Record<string, any>;
9
+ useFastRefresh?: boolean;
10
+ relayArtifactDirectory?: string;
11
+ configureWebpack?: (config: Configuration, env: 'development' | 'production' | 'test') => Configuration;
12
+ };
13
+
14
+ export type HeadConfigType = {
15
+ title: string;
16
+ };
17
+
18
+ export const defaultDevConfig = {
19
+ port: 3000,
20
+ host: '0.0.0.0',
21
+ head: {
22
+ title: 'Apollion',
23
+ },
24
+ constants: {},
25
+ i18nConfig: {},
26
+ useFastRefresh: true,
27
+ };