├── .gitignore ├── .husky ├── .gitignore └── pre-commit ├── .prettierignore ├── .prettierrc ├── .storybook ├── main.js └── preview.js ├── LICENSE ├── README.md ├── config ├── env.js ├── getHttpsConfig.js ├── jest │ ├── babelTransform.js │ ├── cssTransform.js │ └── fileTransform.js ├── modules.js ├── paths.js ├── pnpTs.js ├── webpack.config.js └── webpackDevServer.config.js ├── contributing.md ├── package.json ├── public ├── binance-favicon.ico ├── binance-logo192.png ├── binance-logo512.png ├── index.html ├── manifest.json └── robots.txt ├── scripts ├── build.js ├── start.js └── test.js ├── src ├── App.css ├── App.js ├── assets │ ├── common │ │ └── index.js │ ├── constants │ │ ├── allMarketStreams.js │ │ ├── allUserStreams.js │ │ ├── cPairs.js │ │ ├── cSymbols.js │ │ ├── futuresSymbols.js │ │ ├── index.js │ │ ├── pairs.js │ │ └── symbols.js │ ├── icons.js │ └── languages │ │ ├── cn.json │ │ └── en.json ├── components │ ├── ErrorBoundary.js │ ├── MarketStreamPanel.css │ ├── MarketStreamPanel.js │ ├── SelectionPanel.js │ ├── StreamMenu.js │ ├── StreamSettingModal.css │ ├── StreamSettingModal.js │ ├── SubscriptionPanel.css │ ├── SubscriptionPanel.js │ ├── TagDisplay.js │ ├── UserStreamPanel.js │ └── index.js ├── endpoints.js ├── i18n.js ├── index.css ├── index.js ├── redux │ ├── actions.js │ ├── configureStore.js │ ├── initials.js │ ├── reducer.js │ └── types.js ├── reportWebVitals.js ├── setupTests.js └── stories │ ├── Introduction.stories.mdx │ ├── StreamMenu.stories.js │ ├── StreamSettingModal.stories.js │ ├── SubscriptionPanel.stories.js │ ├── TagDisplay.stories.js │ └── assets │ ├── code-brackets.svg │ ├── colors.svg │ ├── comments.svg │ ├── direction.svg │ ├── flow.svg │ ├── plugin.svg │ ├── repo.svg │ └── stackalt.svg └── yarn.lock /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | 9 | # Diagnostic reports (https://nodejs.org/api/report.html) 10 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 11 | 12 | # Runtime data 13 | pids 14 | *.pid 15 | *.seed 16 | *.pid.lock 17 | 18 | # Directory for instrumented libs generated by jscoverage/JSCover 19 | lib-cov 20 | 21 | # Coverage directory used by tools like istanbul 22 | coverage 23 | *.lcov 24 | 25 | # nyc test coverage 26 | .nyc_output 27 | 28 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 29 | .grunt 30 | 31 | # Bower dependency directory (https://bower.io/) 32 | bower_components 33 | 34 | # node-waf configuration 35 | .lock-wscript 36 | 37 | # Compiled binary addons (https://nodejs.org/api/addons.html) 38 | build/Release 39 | 40 | # Dependency directories 41 | node_modules/ 42 | jspm_packages/ 43 | 44 | # Snowpack dependency directory (https://snowpack.dev/) 45 | web_modules/ 46 | 47 | # TypeScript cache 48 | *.tsbuildinfo 49 | 50 | # Optional npm cache directory 51 | .npm 52 | 53 | # Optional eslint cache 54 | .eslintcache 55 | 56 | # Microbundle cache 57 | .rpt2_cache/ 58 | .rts2_cache_cjs/ 59 | .rts2_cache_es/ 60 | .rts2_cache_umd/ 61 | 62 | # Optional REPL history 63 | .node_repl_history 64 | 65 | # Output of 'npm pack' 66 | *.tgz 67 | 68 | # Yarn Integrity file 69 | .yarn-integrity 70 | 71 | # dotenv environment variables file 72 | .env 73 | .env.test 74 | 75 | # parcel-bundler cache (https://parceljs.org/) 76 | .cache 77 | .parcel-cache 78 | 79 | # Next.js build output 80 | .next 81 | out 82 | 83 | # Nuxt.js build / generate output 84 | .nuxt 85 | dist 86 | 87 | # Gatsby files 88 | .cache/ 89 | # Comment in the public line in if your project uses Gatsby and not Next.js 90 | # https://nextjs.org/blog/next-9-1#public-directory-support 91 | # public 92 | 93 | # vuepress build output 94 | .vuepress/dist 95 | 96 | # Serverless directories 97 | .serverless/ 98 | 99 | # FuseBox cache 100 | .fusebox/ 101 | 102 | # DynamoDB Local files 103 | .dynamodb/ 104 | 105 | # TernJS port file 106 | .tern-port 107 | 108 | # Stores VSCode versions used for testing VSCode extensions 109 | .vscode-test 110 | 111 | # yarn v2 112 | .yarn/cache 113 | .yarn/unplugged 114 | .yarn/build-state.yml 115 | .yarn/install-state.gz 116 | .pnp.* 117 | 118 | # vscode 119 | .vscode/ 120 | !.vscode/settings.json 121 | !.vscode/tasks.json 122 | !.vscode/launch.json 123 | !.vscode/extensions.json 124 | *.code-workspace 125 | 126 | # Local History for Visual Studio Code 127 | .history/ 128 | 129 | # storybook 130 | storybook-static/ 131 | -------------------------------------------------------------------------------- /.husky/.gitignore: -------------------------------------------------------------------------------- 1 | _ 2 | -------------------------------------------------------------------------------- /.husky/pre-commit: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | . "$(dirname "$0")/_/husky.sh" 3 | 4 | yarn pretty-quick 5 | git add -- . :!build/ -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | build 2 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "printWidth": 100, 3 | "singleQuote": true, 4 | "trailingComma": "none", 5 | "arrowParens": "avoid" 6 | } 7 | -------------------------------------------------------------------------------- /.storybook/main.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | 3 | module.exports = { 4 | stories: ['../src/**/*.stories.mdx', '../src/**/*.stories.@(js|jsx|ts|tsx)'], 5 | addons: ['@storybook/addon-links', '@storybook/addon-essentials'], 6 | webpackFinal: async config => { 7 | return { 8 | ...config, 9 | resolve: { 10 | ...config.resolve, 11 | alias: { 12 | ...config.resolve?.alias, 13 | '@common': path.resolve(__dirname, '../src/assets/common'), 14 | '@constants': path.resolve(__dirname, '../src/assets/constants'), 15 | '@ant-design/icons/lib/dist$': path.resolve(__dirname, '../src/assets/icons.js') 16 | } 17 | } 18 | }; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /.storybook/preview.js: -------------------------------------------------------------------------------- 1 | import 'antd/dist/antd.css'; 2 | 3 | export const parameters = { 4 | actions: { argTypesRegex: '^on[A-Z].*' }, 5 | controls: { 6 | matchers: { 7 | color: /(background|color)$/i, 8 | date: /Date$/ 9 | } 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 ishuen 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Websocket Demo [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) 2 | 3 | ![img](https://imgur.com/LzSD4nG.png[/img] 'init screen') 4 | 5 | This web app is developed to simplify the binance websocket stream testing process. By utilizing the interface, the user can check on multiple streams at a time without knowing the parameters. Since this app is designed for testing purpose instead of the real subscription tool, **_all the subscribed streams will be unsubscribed in 5 sec._** 6 | 7 | The left hand side of the screen has 2 parts. The upper is for user stream subscription. The user can select one of the user streams to subscribe given the valid listen key generated based on the api key. The lower is the market stream selection area. The user can only select the streams under the same data source. That is, once the user select a spot market stream, to select from other source, such as coin-m futures stream, is not allowed. 8 | 9 | **Note: Some of the symbols are only available in PRODUCTION.** 10 | 11 | ## Demo Site 12 | 13 | - [Current Deployed Page](https://binance.github.io/websocket-demo) 14 | 15 | ## Usage 16 | 17 | ### Initialize Your Local Environment 18 | 19 | 1. Download the repo 20 | 21 | 2. Turn on the terminal and execute the following commands 22 | 23 | ``` 24 | $ cd 25 | $ yarn install 26 | $ yarn start 27 | ``` 28 | 29 | 3. Open your browser and access `localhost:3000` 30 | 31 | ### Subscribe the User Data Stream 32 | 33 | ![img](https://i.imgur.com/pMo5t3P.png[/img] 'user data stream') 34 | 35 | 1. Use RESTful API to generate the listen key and paste the key to the "Listen key" input box. (If you don't know how to generate the key, please check the API document in "Reference" section below.) 36 | 2. Select the data source from the drop-down list 37 | 3. Click the corresponding subscribe button. 38 | 39 | ### Subscribe Market Streams 40 | 41 | ![img](https://i.imgur.com/dTiRzVh.png[/img] 'market streams') 42 | 43 | 1. Select the data source from the market stream section 44 | 2. Select the stream(s) to subscribe from the drop-down list. If there is any parameter has to be settled, a modal with drop-down list(s) will show up. 45 | 3. Click the testnet or production subscribe button. 46 | 47 | ## Available Scripts 48 | 49 | In the project directory, you can run: 50 | 51 | #### `yarn start` 52 | 53 | Runs the app in the development mode.\ 54 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser. 55 | 56 | The page will reload if you make edits.\ 57 | You will also see any lint errors in the console. 58 | 59 | #### `yarn test` [TODO] 60 | 61 | Launches the test runner in the interactive watch mode.\ 62 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. 63 | 64 | #### `yarn build` 65 | 66 | Builds the app for production to the `build` folder.\ 67 | It correctly bundles React in production mode and optimizes the build for the best performance. 68 | 69 | The build is minified and the filenames include the hashes.\ 70 | Your app is ready to be deployed! 71 | 72 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. 73 | 74 | #### `yarn pretty-quick` 75 | 76 | Runs the code formatter. This command is also hooked with the pre-commit. 77 | 78 | #### `yarn storybook` 79 | 80 | Runs the storybook for component overview.\ 81 | Open [http://localhost:6006](http://localhost:6006) to view it in the browser. 82 | 83 | #### `yarn build-storybook` 84 | 85 | Builds Storybook as a static web application. 86 | 87 | ## Reference 88 | 89 | - [Binance API doc](https://binance-docs.github.io/apidocs/spot/en/#websocket-market-streams) 90 | -------------------------------------------------------------------------------- /config/env.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const fs = require('fs'); 4 | const path = require('path'); 5 | const paths = require('./paths'); 6 | 7 | // Make sure that including paths.js after env.js will read .env variables. 8 | delete require.cache[require.resolve('./paths')]; 9 | 10 | const NODE_ENV = process.env.NODE_ENV; 11 | if (!NODE_ENV) { 12 | throw new Error('The NODE_ENV environment variable is required but was not specified.'); 13 | } 14 | 15 | // https://github.com/bkeepers/dotenv#what-other-env-files-can-i-use 16 | const dotenvFiles = [ 17 | `${paths.dotenv}.${NODE_ENV}.local`, 18 | // Don't include `.env.local` for `test` environment 19 | // since normally you expect tests to produce the same 20 | // results for everyone 21 | NODE_ENV !== 'test' && `${paths.dotenv}.local`, 22 | `${paths.dotenv}.${NODE_ENV}`, 23 | paths.dotenv 24 | ].filter(Boolean); 25 | 26 | // Load environment variables from .env* files. Suppress warnings using silent 27 | // if this file is missing. dotenv will never modify any environment variables 28 | // that have already been set. Variable expansion is supported in .env files. 29 | // https://github.com/motdotla/dotenv 30 | // https://github.com/motdotla/dotenv-expand 31 | dotenvFiles.forEach(dotenvFile => { 32 | if (fs.existsSync(dotenvFile)) { 33 | require('dotenv-expand')( 34 | require('dotenv').config({ 35 | path: dotenvFile 36 | }) 37 | ); 38 | } 39 | }); 40 | 41 | // We support resolving modules according to `NODE_PATH`. 42 | // This lets you use absolute paths in imports inside large monorepos: 43 | // https://github.com/facebook/create-react-app/issues/253. 44 | // It works similar to `NODE_PATH` in Node itself: 45 | // https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders 46 | // Note that unlike in Node, only *relative* paths from `NODE_PATH` are honored. 47 | // Otherwise, we risk importing Node.js core modules into an app instead of webpack shims. 48 | // https://github.com/facebook/create-react-app/issues/1023#issuecomment-265344421 49 | // We also resolve them to make sure all tools using them work consistently. 50 | const appDirectory = fs.realpathSync(process.cwd()); 51 | process.env.NODE_PATH = (process.env.NODE_PATH || '') 52 | .split(path.delimiter) 53 | .filter(folder => folder && !path.isAbsolute(folder)) 54 | .map(folder => path.resolve(appDirectory, folder)) 55 | .join(path.delimiter); 56 | 57 | // Grab NODE_ENV and REACT_APP_* environment variables and prepare them to be 58 | // injected into the application via DefinePlugin in webpack configuration. 59 | const REACT_APP = /^REACT_APP_/i; 60 | 61 | function getClientEnvironment(publicUrl) { 62 | const raw = Object.keys(process.env) 63 | .filter(key => REACT_APP.test(key)) 64 | .reduce( 65 | (env, key) => { 66 | env[key] = process.env[key]; 67 | return env; 68 | }, 69 | { 70 | // Useful for determining whether we’re running in production mode. 71 | // Most importantly, it switches React into the correct mode. 72 | NODE_ENV: process.env.NODE_ENV || 'development', 73 | // Useful for resolving the correct path to static assets in `public`. 74 | // For example, . 75 | // This should only be used as an escape hatch. Normally you would put 76 | // images into the `src` and `import` them in code to get their paths. 77 | PUBLIC_URL: publicUrl, 78 | // We support configuring the sockjs pathname during development. 79 | // These settings let a developer run multiple simultaneous projects. 80 | // They are used as the connection `hostname`, `pathname` and `port` 81 | // in webpackHotDevClient. They are used as the `sockHost`, `sockPath` 82 | // and `sockPort` options in webpack-dev-server. 83 | WDS_SOCKET_HOST: process.env.WDS_SOCKET_HOST, 84 | WDS_SOCKET_PATH: process.env.WDS_SOCKET_PATH, 85 | WDS_SOCKET_PORT: process.env.WDS_SOCKET_PORT, 86 | // Whether or not react-refresh is enabled. 87 | // react-refresh is not 100% stable at this time, 88 | // which is why it's disabled by default. 89 | // It is defined here so it is available in the webpackHotDevClient. 90 | FAST_REFRESH: process.env.FAST_REFRESH !== 'false' 91 | } 92 | ); 93 | // Stringify all values so we can feed into webpack DefinePlugin 94 | const stringified = { 95 | 'process.env': Object.keys(raw).reduce((env, key) => { 96 | env[key] = JSON.stringify(raw[key]); 97 | return env; 98 | }, {}) 99 | }; 100 | 101 | return { raw, stringified }; 102 | } 103 | 104 | module.exports = getClientEnvironment; 105 | -------------------------------------------------------------------------------- /config/getHttpsConfig.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const fs = require('fs'); 4 | const path = require('path'); 5 | const crypto = require('crypto'); 6 | const chalk = require('react-dev-utils/chalk'); 7 | const paths = require('./paths'); 8 | 9 | // Ensure the certificate and key provided are valid and if not 10 | // throw an easy to debug error 11 | function validateKeyAndCerts({ cert, key, keyFile, crtFile }) { 12 | let encrypted; 13 | try { 14 | // publicEncrypt will throw an error with an invalid cert 15 | encrypted = crypto.publicEncrypt(cert, Buffer.from('test')); 16 | } catch (err) { 17 | throw new Error(`The certificate "${chalk.yellow(crtFile)}" is invalid.\n${err.message}`); 18 | } 19 | 20 | try { 21 | // privateDecrypt will throw an error with an invalid key 22 | crypto.privateDecrypt(key, encrypted); 23 | } catch (err) { 24 | throw new Error(`The certificate key "${chalk.yellow(keyFile)}" is invalid.\n${err.message}`); 25 | } 26 | } 27 | 28 | // Read file and throw an error if it doesn't exist 29 | function readEnvFile(file, type) { 30 | if (!fs.existsSync(file)) { 31 | throw new Error( 32 | `You specified ${chalk.cyan(type)} in your env, but the file "${chalk.yellow( 33 | file 34 | )}" can't be found.` 35 | ); 36 | } 37 | return fs.readFileSync(file); 38 | } 39 | 40 | // Get the https config 41 | // Return cert files if provided in env, otherwise just true or false 42 | function getHttpsConfig() { 43 | const { SSL_CRT_FILE, SSL_KEY_FILE, HTTPS } = process.env; 44 | const isHttps = HTTPS === 'true'; 45 | 46 | if (isHttps && SSL_CRT_FILE && SSL_KEY_FILE) { 47 | const crtFile = path.resolve(paths.appPath, SSL_CRT_FILE); 48 | const keyFile = path.resolve(paths.appPath, SSL_KEY_FILE); 49 | const config = { 50 | cert: readEnvFile(crtFile, 'SSL_CRT_FILE'), 51 | key: readEnvFile(keyFile, 'SSL_KEY_FILE') 52 | }; 53 | 54 | validateKeyAndCerts({ ...config, keyFile, crtFile }); 55 | return config; 56 | } 57 | return isHttps; 58 | } 59 | 60 | module.exports = getHttpsConfig; 61 | -------------------------------------------------------------------------------- /config/jest/babelTransform.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const babelJest = require('babel-jest'); 4 | 5 | const hasJsxRuntime = (() => { 6 | if (process.env.DISABLE_NEW_JSX_TRANSFORM === 'true') { 7 | return false; 8 | } 9 | 10 | try { 11 | require.resolve('react/jsx-runtime'); 12 | return true; 13 | } catch (e) { 14 | return false; 15 | } 16 | })(); 17 | 18 | module.exports = babelJest.createTransformer({ 19 | presets: [ 20 | [ 21 | require.resolve('babel-preset-react-app'), 22 | { 23 | runtime: hasJsxRuntime ? 'automatic' : 'classic' 24 | } 25 | ] 26 | ], 27 | babelrc: false, 28 | configFile: false 29 | }); 30 | -------------------------------------------------------------------------------- /config/jest/cssTransform.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // This is a custom Jest transformer turning style imports into empty objects. 4 | // http://facebook.github.io/jest/docs/en/webpack.html 5 | 6 | module.exports = { 7 | process() { 8 | return 'module.exports = {};'; 9 | }, 10 | getCacheKey() { 11 | // The output is always the same. 12 | return 'cssTransform'; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /config/jest/fileTransform.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const path = require('path'); 4 | const camelcase = require('camelcase'); 5 | 6 | // This is a custom Jest transformer turning file imports into filenames. 7 | // http://facebook.github.io/jest/docs/en/webpack.html 8 | 9 | module.exports = { 10 | process(src, filename) { 11 | const assetFilename = JSON.stringify(path.basename(filename)); 12 | 13 | if (filename.match(/\.svg$/)) { 14 | // Based on how SVGR generates a component name: 15 | // https://github.com/smooth-code/svgr/blob/01b194cf967347d43d4cbe6b434404731b87cf27/packages/core/src/state.js#L6 16 | const pascalCaseFilename = camelcase(path.parse(filename).name, { 17 | pascalCase: true 18 | }); 19 | const componentName = `Svg${pascalCaseFilename}`; 20 | return `const React = require('react'); 21 | module.exports = { 22 | __esModule: true, 23 | default: ${assetFilename}, 24 | ReactComponent: React.forwardRef(function ${componentName}(props, ref) { 25 | return { 26 | $$typeof: Symbol.for('react.element'), 27 | type: 'svg', 28 | ref: ref, 29 | key: null, 30 | props: Object.assign({}, props, { 31 | children: ${assetFilename} 32 | }) 33 | }; 34 | }), 35 | };`; 36 | } 37 | 38 | return `module.exports = ${assetFilename};`; 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /config/modules.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const fs = require('fs'); 4 | const path = require('path'); 5 | const paths = require('./paths'); 6 | const chalk = require('react-dev-utils/chalk'); 7 | const resolve = require('resolve'); 8 | 9 | /** 10 | * Get additional module paths based on the baseUrl of a compilerOptions object. 11 | * 12 | * @param {Object} options 13 | */ 14 | function getAdditionalModulePaths(options = {}) { 15 | const baseUrl = options.baseUrl; 16 | 17 | if (!baseUrl) { 18 | return ''; 19 | } 20 | 21 | const baseUrlResolved = path.resolve(paths.appPath, baseUrl); 22 | 23 | // We don't need to do anything if `baseUrl` is set to `node_modules`. This is 24 | // the default behavior. 25 | if (path.relative(paths.appNodeModules, baseUrlResolved) === '') { 26 | return null; 27 | } 28 | 29 | // Allow the user set the `baseUrl` to `appSrc`. 30 | if (path.relative(paths.appSrc, baseUrlResolved) === '') { 31 | return [paths.appSrc]; 32 | } 33 | 34 | // If the path is equal to the root directory we ignore it here. 35 | // We don't want to allow importing from the root directly as source files are 36 | // not transpiled outside of `src`. We do allow importing them with the 37 | // absolute path (e.g. `src/Components/Button.js`) but we set that up with 38 | // an alias. 39 | if (path.relative(paths.appPath, baseUrlResolved) === '') { 40 | return null; 41 | } 42 | 43 | // Otherwise, throw an error. 44 | throw new Error( 45 | chalk.red.bold( 46 | "Your project's `baseUrl` can only be set to `src` or `node_modules`." + 47 | ' Create React App does not support other values at this time.' 48 | ) 49 | ); 50 | } 51 | 52 | /** 53 | * Get webpack aliases based on the baseUrl of a compilerOptions object. 54 | * 55 | * @param {*} options 56 | */ 57 | function getWebpackAliases(options = {}) { 58 | const baseUrl = options.baseUrl; 59 | 60 | if (!baseUrl) { 61 | return {}; 62 | } 63 | 64 | const baseUrlResolved = path.resolve(paths.appPath, baseUrl); 65 | 66 | if (path.relative(paths.appPath, baseUrlResolved) === '') { 67 | return { 68 | src: paths.appSrc 69 | }; 70 | } 71 | } 72 | 73 | /** 74 | * Get jest aliases based on the baseUrl of a compilerOptions object. 75 | * 76 | * @param {*} options 77 | */ 78 | function getJestAliases(options = {}) { 79 | const baseUrl = options.baseUrl; 80 | 81 | if (!baseUrl) { 82 | return {}; 83 | } 84 | 85 | const baseUrlResolved = path.resolve(paths.appPath, baseUrl); 86 | 87 | if (path.relative(paths.appPath, baseUrlResolved) === '') { 88 | return { 89 | '^src/(.*)$': '/src/$1' 90 | }; 91 | } 92 | } 93 | 94 | function getModules() { 95 | // Check if TypeScript is setup 96 | const hasTsConfig = fs.existsSync(paths.appTsConfig); 97 | const hasJsConfig = fs.existsSync(paths.appJsConfig); 98 | 99 | if (hasTsConfig && hasJsConfig) { 100 | throw new Error( 101 | 'You have both a tsconfig.json and a jsconfig.json. If you are using TypeScript please remove your jsconfig.json file.' 102 | ); 103 | } 104 | 105 | let config; 106 | 107 | // If there's a tsconfig.json we assume it's a 108 | // TypeScript project and set up the config 109 | // based on tsconfig.json 110 | if (hasTsConfig) { 111 | const ts = require(resolve.sync('typescript', { 112 | basedir: paths.appNodeModules 113 | })); 114 | config = ts.readConfigFile(paths.appTsConfig, ts.sys.readFile).config; 115 | // Otherwise we'll check if there is jsconfig.json 116 | // for non TS projects. 117 | } else if (hasJsConfig) { 118 | config = require(paths.appJsConfig); 119 | } 120 | 121 | config = config || {}; 122 | const options = config.compilerOptions || {}; 123 | 124 | const additionalModulePaths = getAdditionalModulePaths(options); 125 | 126 | return { 127 | additionalModulePaths: additionalModulePaths, 128 | webpackAliases: getWebpackAliases(options), 129 | jestAliases: getJestAliases(options), 130 | hasTsConfig 131 | }; 132 | } 133 | 134 | module.exports = getModules(); 135 | -------------------------------------------------------------------------------- /config/paths.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const path = require('path'); 4 | const fs = require('fs'); 5 | const getPublicUrlOrPath = require('react-dev-utils/getPublicUrlOrPath'); 6 | 7 | // Make sure any symlinks in the project folder are resolved: 8 | // https://github.com/facebook/create-react-app/issues/637 9 | const appDirectory = fs.realpathSync(process.cwd()); 10 | const resolveApp = relativePath => path.resolve(appDirectory, relativePath); 11 | 12 | // We use `PUBLIC_URL` environment variable or "homepage" field to infer 13 | // "public path" at which the app is served. 14 | // webpack needs to know it to put the right