repo stringlengths 5 106 | file_url stringlengths 78 301 | file_path stringlengths 4 211 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 14:56:49 2026-01-05 02:23:25 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/test/fixtures/global-scss-asset-resolution/src/index.js | test/fixtures/global-scss-asset-resolution/src/index.js | import React from 'react';
import ReactDOM from 'react-dom';
import './index.scss';
ReactDOM.render(<div />, document.getElementById('root'));
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/test/fixtures/builds-with-multiple-runtimes/index.test.js | test/fixtures/builds-with-multiple-runtimes/index.test.js | 'use strict';
const testSetup = require('../__shared__/test-setup');
test('builds in development', async () => {
const { fulfilled } = await testSetup.scripts.start({ smoke: true });
expect(fulfilled).toBe(true);
});
test('builds in production', async () => {
const { fulfilled } = await testSetup.scripts.build();
expect(fulfilled).toBe(true);
});
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/test/fixtures/builds-with-multiple-runtimes/src/index.js | test/fixtures/builds-with-multiple-runtimes/src/index.js | import React from 'react';
import dva from 'dva';
import createHistory from 'history/createHashHistory';
import ky from 'ky';
const app = dva({ history: createHistory() });
app.router(() => {
ky.get('https://canihazip.com/s')
.then(r => r.text())
.then(console.log, console.error)
.then(() => console.log('ok'));
return <div>Test</div>;
});
app.start('#root');
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/test/fixtures/webpack-message-formatting/index.test.js | test/fixtures/webpack-message-formatting/index.test.js | 'use strict';
const testSetup = require('../__shared__/test-setup');
const fs = require('fs-extra');
const path = require('path');
test('formats babel syntax error', async () => {
fs.copySync(
path.join(__dirname, 'src', 'AppBabel.js'),
path.join(testSetup.testDirectory, 'src', 'App.js')
);
const { stdout, stderr } = await testSetup.scripts.build();
expect({ stdout, stderr }).toMatchSnapshot();
});
test('formats css syntax error', async () => {
fs.copySync(
path.join(__dirname, 'src', 'AppCss.js'),
path.join(testSetup.testDirectory, 'src', 'App.js')
);
const { stdout, stderr } = await testSetup.scripts.build();
expect({ stdout, stderr }).toMatchSnapshot();
});
test('formats unknown export', async () => {
fs.copySync(
path.join(__dirname, 'src', 'AppUnknownExport.js'),
path.join(testSetup.testDirectory, 'src', 'App.js')
);
const { stdout, stderr } = await testSetup.scripts.build();
expect({ stdout, stderr }).toMatchSnapshot();
});
test('formats aliased unknown export', async () => {
fs.copySync(
path.join(__dirname, 'src', 'AppAliasUnknownExport.js'),
path.join(testSetup.testDirectory, 'src', 'App.js')
);
const { stdout, stderr } = await testSetup.scripts.build();
expect({ stdout, stderr }).toMatchSnapshot();
});
test('formats no default export', async () => {
fs.copySync(
path.join(__dirname, 'src', 'AppNoDefault.js'),
path.join(testSetup.testDirectory, 'src', 'App.js')
);
const { stdout, stderr } = await testSetup.scripts.build();
expect({ stdout, stderr }).toMatchSnapshot();
});
test('formats missing package', async () => {
fs.copySync(
path.join(__dirname, 'src', 'AppMissingPackage.js'),
path.join(testSetup.testDirectory, 'src', 'App.js')
);
let { stdout, stderr } = await testSetup.scripts.build();
if (process.platform === 'win32') {
stderr = stderr.replace('.\\src\\App.js', './src/App.js');
}
expect({ stdout, stderr }).toMatchSnapshot();
});
test('formats eslint warning', async () => {
fs.copySync(
path.join(__dirname, 'src', 'AppLintWarning.js'),
path.join(testSetup.testDirectory, 'src', 'App.js')
);
let { stdout, stderr } = await testSetup.scripts.build();
const sizeIndex = stdout.indexOf('File sizes after gzip');
if (sizeIndex !== -1) {
stdout = stdout.substring(0, sizeIndex);
}
expect({ stdout, stderr }).toMatchSnapshot();
});
test('formats eslint error', async () => {
fs.copySync(
path.join(__dirname, 'src', 'AppLintError.js'),
path.join(testSetup.testDirectory, 'src', 'App.js')
);
const { stdout, stderr } = await testSetup.scripts.build();
expect({ stdout, stderr }).toMatchSnapshot();
});
test('helps when users tries to use sass', async () => {
fs.copySync(
path.join(__dirname, 'src', 'AppSass.js'),
path.join(testSetup.testDirectory, 'src', 'App.js')
);
const { stdout, stderr } = await testSetup.scripts.build();
expect(stdout).toBeFalsy();
// TODO: Snapshots differ between Node 10/12 as the call stack log output has changed.
expect(stderr).toContain(
'To import Sass files, you first need to install sass.'
);
});
test('formats file not found error', async () => {
fs.copySync(
path.join(__dirname, 'src', 'AppUnknownFile.js'),
path.join(testSetup.testDirectory, 'src', 'App.js')
);
let { stdout, stderr } = await testSetup.scripts.build();
if (process.platform === 'win32') {
stderr = stderr
.replace('.\\src\\App.js', './src/App.js')
.replace('.\\src', './src');
}
expect({ stdout, stderr }).toMatchSnapshot();
});
test('formats case sensitive path error', async () => {
fs.copySync(
path.join(__dirname, 'src', 'AppIncorrectCase.js'),
path.join(testSetup.testDirectory, 'src', 'App.js')
);
const { stderr } = await testSetup.scripts.start({ smoke: true });
if (process.platform === 'darwin') {
// eslint-disable-next-line jest/no-conditional-expect
expect(stderr).toMatch(
`Cannot find file: 'export5.js' does not match the corresponding name on disk: './src/Export5.js'.`
);
} else {
// eslint-disable-next-line jest/no-conditional-expect
expect(stderr).not.toEqual(''); // TODO: figure out how we can test this on Linux/Windows
// I believe getting this working requires we tap into enhanced-resolve
// pipeline, which is debt we don't want to take on right now.
}
});
test('formats out of scope error', async () => {
fs.copySync(
path.join(__dirname, 'src', 'AppOutOfScopeImport.js'),
path.join(testSetup.testDirectory, 'src', 'App.js')
);
let { stdout, stderr } = await testSetup.scripts.build();
if (process.platform === 'win32') {
stderr = stderr.replace('.\\src\\App.js', './src/App.js');
}
expect({ stdout, stderr }).toMatchSnapshot();
});
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/test/fixtures/webpack-message-formatting/src/FooExport.js | test/fixtures/webpack-message-formatting/src/FooExport.js | export function foo() {
console.log('bar');
}
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/test/fixtures/webpack-message-formatting/src/AppUnknownFile.js | test/fixtures/webpack-message-formatting/src/AppUnknownFile.js | import React, { Component } from 'react';
import DefaultExport from './ThisFileSouldNotExist';
class App extends Component {
render() {
return <div className="App" />;
}
}
export default App;
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/test/fixtures/webpack-message-formatting/src/AppLintError.js | test/fixtures/webpack-message-formatting/src/AppLintError.js | import React, { Component } from 'react';
function foo() {
const a = b;
}
class App extends Component {
render() {
return <div />;
}
}
export default App;
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/test/fixtures/webpack-message-formatting/src/index.js | test/fixtures/webpack-message-formatting/src/index.js | import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(<App />, document.getElementById('root'));
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/test/fixtures/webpack-message-formatting/src/AppLintWarning.js | test/fixtures/webpack-message-formatting/src/AppLintWarning.js | import React, { Component } from 'react';
function foo() {}
class App extends Component {
render() {
return <div />;
}
}
export default App;
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/test/fixtures/webpack-message-formatting/src/AppNoDefault.js | test/fixtures/webpack-message-formatting/src/AppNoDefault.js | import React, { Component } from 'react';
import myImport from './ExportNoDefault';
class App extends Component {
render() {
return <div className="App">{myImport}</div>;
}
}
export default App;
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/test/fixtures/webpack-message-formatting/src/Export5.js | test/fixtures/webpack-message-formatting/src/Export5.js | export default 5;
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/test/fixtures/webpack-message-formatting/src/AppOutOfScopeImport.js | test/fixtures/webpack-message-formatting/src/AppOutOfScopeImport.js | import React, { Component } from 'react';
import myImport from '../OutOfScopeImport';
class App extends Component {
render() {
return <div className="App">{myImport}</div>;
}
}
export default App;
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/test/fixtures/webpack-message-formatting/src/AppBabel.js | test/fixtures/webpack-message-formatting/src/AppBabel.js | import React, { Component } from 'react';
class App extends Component {
render() {
return (
<div>
<span>
</div>
);
}
}
export default App;
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/test/fixtures/webpack-message-formatting/src/AppSass.js | test/fixtures/webpack-message-formatting/src/AppSass.js | import React, { Component } from 'react';
import './AppSass.scss';
class App extends Component {
render() {
return <div className="App" />;
}
}
export default App;
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/test/fixtures/webpack-message-formatting/src/AppUnknownExport.js | test/fixtures/webpack-message-formatting/src/AppUnknownExport.js | import React, { Component } from 'react';
import { bar } from './AppUnknownExport';
class App extends Component {
componentDidMount() {
bar();
}
render() {
return <div />;
}
}
export default App;
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/test/fixtures/webpack-message-formatting/src/AppIncorrectCase.js | test/fixtures/webpack-message-formatting/src/AppIncorrectCase.js | import React, { Component } from 'react';
import five from './export5';
class App extends Component {
render() {
return <div className="App">{five}</div>;
}
}
export default App;
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/test/fixtures/webpack-message-formatting/src/AppMissingPackage.js | test/fixtures/webpack-message-formatting/src/AppMissingPackage.js | import React, { Component } from 'react';
import { bar } from 'unknown-package';
class App extends Component {
componentDidMount() {
bar();
}
render() {
return <div />;
}
}
export default App;
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/test/fixtures/webpack-message-formatting/src/ExportNoDefault.js | test/fixtures/webpack-message-formatting/src/ExportNoDefault.js | export const six = 6;
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/test/fixtures/webpack-message-formatting/src/AppAliasUnknownExport.js | test/fixtures/webpack-message-formatting/src/AppAliasUnknownExport.js | import React, { Component } from 'react';
import { bar as bar2 } from './AppUnknownExport';
class App extends Component {
componentDidMount() {
bar2();
}
render() {
return <div />;
}
}
export default App;
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/test/fixtures/webpack-message-formatting/src/AppCss.js | test/fixtures/webpack-message-formatting/src/AppCss.js | import React, { Component } from 'react';
import './AppCss.css';
class App extends Component {
render() {
return <div className="App" />;
}
}
export default App;
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/test/fixtures/typescript/index.test.js | test/fixtures/typescript/index.test.js | 'use strict';
const testSetup = require('../__shared__/test-setup');
test('passes tests', async () => {
const { fulfilled } = await testSetup.scripts.test({
jestEnvironment: 'node',
});
expect(fulfilled).toBe(true);
});
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/test/fixtures/relative-paths/index.test.js | test/fixtures/relative-paths/index.test.js | 'use strict';
const testSetup = require('../__shared__/test-setup');
const fs = require('fs-extra');
const globby = require('globby');
const path = require('path');
test('contains a relative path in production build', async () => {
await testSetup.scripts.build();
const buildDir = path.join(testSetup.testDirectory, 'build');
const cssFile = path.join(
buildDir,
globby.sync('**/*.css', { cwd: buildDir }).pop()
);
const svgFile = path.join(
buildDir,
globby.sync('**/*.svg', { cwd: buildDir }).pop()
);
const desiredPath = /url\((.+?)\)/
.exec(fs.readFileSync(cssFile, 'utf8'))
.pop();
expect(path.resolve(path.join(path.dirname(cssFile), desiredPath))).toBe(
path.resolve(svgFile)
);
});
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/test/fixtures/relative-paths/src/index.js | test/fixtures/relative-paths/src/index.js | import './index.css';
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/test/fixtures/issue-5947-not-typescript/index.test.js | test/fixtures/issue-5947-not-typescript/index.test.js | 'use strict';
const testSetup = require('../__shared__/test-setup');
const path = require('path');
const fs = require('fs');
test('Ignores node_modules when detecting TypeScript', async () => {
// CRA build will check for TypeScript files by
// globbing for src/**/*.ts however this shouldn't
// include any node_modules directories within src.
// See https://github.com/facebook/create-react-app/issues/5947
const tsConfigPath = path.join(testSetup.testDirectory, 'tsconfig.json');
const tsPackagePath = [
testSetup.testDirectory,
'src',
'node_modules',
'package',
'index.ts',
];
const dtsSrcPath = [testSetup.testDirectory, 'src', 'types', 'index.d.ts'];
const tsSrcPath = path.join(testSetup.testDirectory, 'src', 'index.ts');
// Step 1.
// See if src/node_modules/package/index.ts is treated
// as a JS project
fs.mkdirSync(path.join(...tsPackagePath.slice(0, 2)));
fs.mkdirSync(path.join(...tsPackagePath.slice(0, 3)));
fs.mkdirSync(path.join(...tsPackagePath.slice(0, 4)));
fs.writeFileSync(path.join(...tsPackagePath));
await testSetup.scripts.build();
expect(fs.existsSync(tsConfigPath)).toBe(false);
// Step 1b.
// See if src/types/index.d.ts is treated as a JS project
fs.mkdirSync(path.join(...dtsSrcPath.slice(0, 3)));
fs.writeFileSync(path.join(...dtsSrcPath));
await testSetup.scripts.build();
expect(fs.existsSync(tsConfigPath)).toBe(false);
// Step 2.
// Add TS and ensure tsconfig.json is generated
fs.writeFileSync(tsSrcPath);
await testSetup.scripts.build();
expect(fs.existsSync(tsConfigPath)).toBe(true);
});
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/docusaurus/website/docusaurus.config.js | docusaurus/website/docusaurus.config.js | /**
* Copyright (c) 2017-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
const siteConfig = {
title: 'Create React App',
tagline:
'Create React App has been deprecated. Please visit react.dev for modern options.',
url: 'https://create-react-app.dev',
baseUrl: '/',
projectName: 'create-react-app',
organizationName: 'facebook',
favicon: 'img/favicon/favicon.ico',
presets: [
[
'@docusaurus/preset-classic',
{
docs: {
path: '../docs',
sidebarPath: require.resolve('./sidebars.json'),
editUrl:
'https://github.com/facebook/create-react-app/edit/main/docusaurus/website',
showLastUpdateAuthor: true,
showLastUpdateTime: true,
},
theme: {
customCss: require.resolve('./src/css/custom.css'),
},
},
],
],
themeConfig: {
image: 'img/logo-og.png',
announcementBar: {
id: 'deprecated',
content:
'Create React App is deprecated. <a target="_blank" rel="noopener noreferrer" href="https://react.dev/link/cra">Read more here</a>.',
backgroundColor: '#20232a',
textColor: '#fff',
isCloseable: false,
},
algolia: {
appId: 'AUJYIQ70HN',
apiKey: '25243dbf9049cf036e87f64b361bd2b9',
indexName: 'create-react-app',
},
navbar: {
title: 'Create React App',
logo: {
alt: 'Create React App Logo',
src: 'img/logo.svg',
},
items: [
{ to: 'docs/getting-started', label: 'Docs', position: 'right' },
{
href: 'https://reactjs.org/community/support.html',
label: 'Help',
position: 'right',
},
{
href: 'https://www.github.com/facebook/create-react-app',
label: 'GitHub',
position: 'right',
},
],
},
footer: {
style: 'dark',
links: [
{
title: 'Docs',
items: [
{
label: 'Get Started',
to: 'docs/getting-started',
},
{
label: 'Learn React',
href: 'https://reactjs.org/',
},
],
},
{
title: 'Community',
items: [
{
label: 'Stack Overflow',
href: 'https://stackoverflow.com/questions/tagged/create-react-app',
},
{
label: 'GitHub Discussions',
href: 'https://github.com/facebook/create-react-app/discussions',
},
{
label: 'Twitter',
href: 'https://twitter.com/reactjs',
},
{
label: 'Contributor Covenant',
href: 'https://www.contributor-covenant.org/version/1/4/code-of-conduct',
},
],
},
{
title: 'Social',
items: [
{
label: 'GitHub',
href: 'https://www.github.com/facebook/create-react-app',
},
],
},
],
logo: {
alt: 'Facebook Open Source Logo',
src: 'img/oss_logo.png',
},
copyright: `Copyright © ${new Date().getFullYear()} Facebook, Inc.`,
},
},
};
module.exports = siteConfig;
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/docusaurus/website/src/pages/index.js | docusaurus/website/src/pages/index.js | /**
* Copyright (c) 2017-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import Link from '@docusaurus/Link';
import Head from '@docusaurus/Head';
import useDocusaurusContext from '@docusaurus/useDocusaurusContext';
import useBaseUrl from '@docusaurus/useBaseUrl';
import Layout from '@theme/Layout';
import CodeBlock from '@theme/CodeBlock';
import clsx from 'clsx';
import styles from './styles.module.css';
const features = [
{
title: 'Less to Learn',
content:
"You don't need to learn and configure many build tools. Instant reloads help you focus on development. When it's time to deploy, your bundles are optimized automatically.",
},
{
title: 'Only One Dependency',
content:
'Your app only needs one build dependency. We test Create React App to make sure that all of its underlying pieces work together seamlessly – no complicated version mismatches.',
},
{
title: 'No Lock-In',
content:
'Under the hood, we use webpack, Babel, ESLint, and other amazing projects to power your app. If you ever want an advanced configuration, you can ”eject” from Create React App and edit their config files directly.',
},
];
function Home() {
const context = useDocusaurusContext();
const { siteConfig = {} } = context;
return (
<Layout
permalink={'/'}
description={'Set up a modern web app by running one command.'}
>
<Head>
<meta name="robots" content="noindex" />
<title>Create React App is deprecated.</title>
<meta
name="description"
content="Create React App is deprecated. Please see react.dev for modern options."
/>
<meta property="og:title" content="Create React App is deprecated." />
<meta
property="og:description"
content="Create React App is deprecated. Please see react.dev for modern options."
/>
</Head>
<div className={clsx('hero hero--dark', styles.heroBanner)}>
<div className="container">
<img
className={clsx(styles.heroBannerLogo, 'margin-vert--md')}
alt="Create React App logo"
src={useBaseUrl('img/logo.svg')}
/>
<h1 className="hero__title">{siteConfig.title}</h1>
<p className="hero__subtitle">{siteConfig.tagline}</p>
<div className={styles.getStarted}>
<Link
className="button button--outline button--primary button--lg"
to={useBaseUrl('docs/getting-started')}
>
Get Started
</Link>
</div>
</div>
</div>
{features && features.length && (
<div className={styles.features}>
<div className="container">
<div className="row">
{features.map(({ title, content }, idx) => (
<div key={idx} className={clsx('col col--4', styles.feature)}>
<h2>{title}</h2>
<p>{content}</p>
</div>
))}
</div>
</div>
</div>
)}
<div className={styles.gettingStartedSection}>
<div className="container padding-vert--xl text--left">
<div className="row">
<div className="col col--4 col--offset-1">
<h2>Get started in seconds</h2>
<p>
Whether you’re using React or another library, Create React App
lets you <strong>focus on code, not build tools</strong>.
<br />
<br />
To create a project called <i>my-app</i>, run this command:
</p>
<CodeBlock className="language-sh">
npx create-react-app my-app
</CodeBlock>
<br />
</div>
<div className="col col--5 col--offset-1">
<img
className={styles.featureImage}
alt="Easy to get started in seconds"
src={
'https://camo.githubusercontent.com/29765c4a32f03bd01d44edef1cd674225e3c906b/68747470733a2f2f63646e2e7261776769742e636f6d2f66616365626f6f6b2f6372656174652d72656163742d6170702f323762343261632f73637265656e636173742e737667'
}
/>
</div>
</div>
</div>
</div>
<div>
<div className="container padding-vert--xl text--left">
<div className="row">
<div className="col col--4 col--offset-1">
<img
className={styles.featureImage}
alt="Easy to update"
src={useBaseUrl('img/update.png')}
/>
</div>
<div className="col col--5 col--offset-1">
<h2>Easy to Maintain</h2>
<p>
Updating your build tooling is typically a daunting and
time-consuming task. When new versions of Create React App are
released, you can upgrade using a single command:
</p>
<CodeBlock className="language-sh">
npm install react-scripts@latest
</CodeBlock>
</div>
</div>
</div>
</div>
</Layout>
);
}
export default Home;
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/babel-plugin-named-asset-import/index.test.js | packages/babel-plugin-named-asset-import/index.test.js | 'use strict';
const pluginTester = require('babel-plugin-tester/pure');
const namedAssetImport = require('./index');
pluginTester.default({
plugin: namedAssetImport,
pluginOptions: {
loaderMap: {
svg: {
ReactComponent: '@svgr/webpack?-svgo![path]',
},
},
},
pluginName: 'named-asset-import',
snapshot: false,
tests: {
defaultImport: {
code: 'import logo from "logo";',
output: 'import logo from "logo";',
},
namedImport: {
code: 'import { logo } from "logo";',
output: 'import { logo } from "logo";',
},
namedImportRenamed: {
code: 'import { Url as logo1 } from "logo";',
output: 'import { Url as logo1 } from "logo";',
},
svgDefaultImport: {
code: 'import logo from "logo.svg";',
output: 'import logo from "logo.svg";',
},
svgNamedImport: {
code: 'import { logo } from "logo.svg";',
output: 'import { logo } from "logo.svg";',
},
svgReactComponentNamedImport: {
code: 'import { ReactComponent as logo } from "logo.svg";',
output:
'import { ReactComponent as logo } from "@svgr/webpack?-svgo!logo.svg";',
},
svgMultipleImport: {
code: 'import logo, { logoUrl , ReactComponent as Logo } from "logo.svg";',
output:
'import logo from "logo.svg";\n' +
'import { logoUrl } from "logo.svg";\n' +
'import { ReactComponent as Logo } from "@svgr/webpack?-svgo!logo.svg";',
},
defaultExport: {
code: 'export default logo;',
output: 'export default logo;',
},
constExport: {
code: 'export const token = "token";',
output: 'export const token = "token";',
},
classExport: {
code: 'export class Logo {}',
output: 'export class Logo {}',
},
namedExport: {
code: 'export { logo } from "logo";',
output: 'export { logo } from "logo";',
},
namedExportRenamed: {
code: 'export { Url as logo } from "logo";',
output: 'export { Url as logo } from "logo";',
},
allExport: {
code: 'export * from "logo";',
output: 'export * from "logo";',
},
svgNamedExport: {
code: 'export { logo } from "logo.svg";',
output: 'export { logo } from "logo.svg";',
},
svgAllExport: {
code: 'export * from "logo.svg";',
output: 'export * from "logo.svg";',
},
svgReactComponentNamedExport: {
code: 'export { ReactComponent as Logo } from "logo.svg";',
output:
'export { ReactComponent as Logo } from "@svgr/webpack?-svgo!logo.svg";',
},
svgReactComponentExport: {
code: 'export { ReactComponent } from "logo.svg";',
output: 'export { ReactComponent } from "@svgr/webpack?-svgo!logo.svg";',
},
svgMultipleExport: {
code: 'export { logoUrl , ReactComponent as Logo } from "logo.svg";',
output:
'export { logoUrl } from "logo.svg";\n' +
'export { ReactComponent as Logo } from "@svgr/webpack?-svgo!logo.svg";',
},
},
});
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/babel-plugin-named-asset-import/index.js | packages/babel-plugin-named-asset-import/index.js | 'use strict';
const { extname } = require('path');
function namedAssetImportPlugin({ types: t }) {
const visited = new WeakSet();
function generateNewSourcePath(loaderMap, moduleName, sourcePath) {
const ext = extname(sourcePath).substr(1);
const extMap = loaderMap[ext];
return extMap[moduleName]
? extMap[moduleName].replace(/\[path\]/, sourcePath)
: sourcePath;
}
function replaceMatchingSpecifiers(path, loaderMap, callback) {
const sourcePath = path.node.source.value;
const ext = extname(sourcePath).substr(1);
if (visited.has(path.node) || sourcePath.indexOf('!') !== -1) {
return;
}
if (loaderMap[ext]) {
path.replaceWithMultiple(
path.node.specifiers.map(specifier => {
const newSpecifier = callback(specifier, sourcePath);
visited.add(newSpecifier);
return newSpecifier;
})
);
}
}
return {
visitor: {
ExportNamedDeclaration(path, { opts: { loaderMap } }) {
if (!path.node.source) {
return;
}
replaceMatchingSpecifiers(path, loaderMap, (specifier, sourcePath) => {
if (t.isExportDefaultSpecifier(specifier)) {
return t.exportDeclaration(
[t.exportDefaultSpecifier(t.identifier(specifier.local.name))],
t.stringLiteral(sourcePath)
);
}
return t.exportNamedDeclaration(
null,
[
t.exportSpecifier(
t.identifier(specifier.local.name),
t.identifier(specifier.exported.name)
),
],
t.stringLiteral(
generateNewSourcePath(loaderMap, specifier.local.name, sourcePath)
)
);
});
},
ImportDeclaration(path, { opts: { loaderMap } }) {
replaceMatchingSpecifiers(path, loaderMap, (specifier, sourcePath) => {
if (t.isImportDefaultSpecifier(specifier)) {
return t.importDeclaration(
[t.importDefaultSpecifier(t.identifier(specifier.local.name))],
t.stringLiteral(sourcePath)
);
}
return t.importDeclaration(
[
t.importSpecifier(
t.identifier(specifier.local.name),
t.identifier(specifier.imported.name)
),
],
t.stringLiteral(
generateNewSourcePath(
loaderMap,
specifier.imported.name,
sourcePath
)
)
);
});
},
},
};
}
module.exports = namedAssetImportPlugin;
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-dev-utils/getProcessForPort.js | packages/react-dev-utils/getProcessForPort.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
var chalk = require('chalk');
var execSync = require('child_process').execSync;
var execFileSync = require('child_process').execFileSync;
var path = require('path');
var execOptions = {
encoding: 'utf8',
stdio: [
'pipe', // stdin (default)
'pipe', // stdout (default)
'ignore', //stderr
],
};
function isProcessAReactApp(processCommand) {
return /^node .*react-scripts\/scripts\/start\.js\s?$/.test(processCommand);
}
function getProcessIdOnPort(port) {
return execFileSync(
'lsof',
['-i:' + port, '-P', '-t', '-sTCP:LISTEN'],
execOptions
)
.split('\n')[0]
.trim();
}
function getPackageNameInDirectory(directory) {
var packagePath = path.join(directory.trim(), 'package.json');
try {
return require(packagePath).name;
} catch (e) {
return null;
}
}
function getProcessCommand(processId, processDirectory) {
var command = execSync(
'ps -o command -p ' + processId + ' | sed -n 2p',
execOptions
);
command = command.replace(/\n$/, '');
if (isProcessAReactApp(command)) {
const packageName = getPackageNameInDirectory(processDirectory);
return packageName ? packageName : command;
} else {
return command;
}
}
function getDirectoryOfProcessById(processId) {
return execSync(
'lsof -p ' +
processId +
' | awk \'$4=="cwd" {for (i=9; i<=NF; i++) printf "%s ", $i}\'',
execOptions
).trim();
}
function getProcessForPort(port) {
try {
var processId = getProcessIdOnPort(port);
var directory = getDirectoryOfProcessById(processId);
var command = getProcessCommand(processId, directory);
return (
chalk.cyan(command) +
chalk.grey(' (pid ' + processId + ')\n') +
chalk.blue(' in ') +
chalk.cyan(directory)
);
} catch (e) {
return null;
}
}
module.exports = getProcessForPort;
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-dev-utils/crossSpawn.js | packages/react-dev-utils/crossSpawn.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
var crossSpawn = require('cross-spawn');
module.exports = crossSpawn;
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-dev-utils/getCacheIdentifier.js | packages/react-dev-utils/getCacheIdentifier.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
module.exports = function getCacheIdentifier(environment, packages) {
let cacheIdentifier = environment == null ? '' : environment.toString();
for (const packageName of packages) {
cacheIdentifier += `:${packageName}@`;
try {
cacheIdentifier += require(`${packageName}/package.json`).version;
} catch (_) {
// ignored
}
}
return cacheIdentifier;
};
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-dev-utils/globby.js | packages/react-dev-utils/globby.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
var globby = require('globby');
module.exports = globby;
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-dev-utils/clearConsole.js | packages/react-dev-utils/clearConsole.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
function clearConsole() {
process.stdout.write(
process.platform === 'win32' ? '\x1B[2J\x1B[0f' : '\x1B[2J\x1B[3J\x1B[H'
);
}
module.exports = clearConsole;
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-dev-utils/launchEditor.js | packages/react-dev-utils/launchEditor.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
const fs = require('fs');
const path = require('path');
const child_process = require('child_process');
const os = require('os');
const chalk = require('chalk');
const shellQuote = require('shell-quote');
function isTerminalEditor(editor) {
switch (editor) {
case 'vim':
case 'emacs':
case 'nano':
return true;
}
return false;
}
// Map from full process name to binary that starts the process
// We can't just re-use full process name, because it will spawn a new instance
// of the app every time
const COMMON_EDITORS_OSX = {
'/Applications/Atom.app/Contents/MacOS/Atom': 'atom',
'/Applications/Atom Beta.app/Contents/MacOS/Atom Beta':
'/Applications/Atom Beta.app/Contents/MacOS/Atom Beta',
'/Applications/Brackets.app/Contents/MacOS/Brackets': 'brackets',
'/Applications/Sublime Text.app/Contents/MacOS/Sublime Text':
'/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl',
'/Applications/Sublime Text Dev.app/Contents/MacOS/Sublime Text':
'/Applications/Sublime Text Dev.app/Contents/SharedSupport/bin/subl',
'/Applications/Sublime Text 2.app/Contents/MacOS/Sublime Text 2':
'/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl',
'/Applications/Visual Studio Code.app/Contents/MacOS/Electron': 'code',
'/Applications/Visual Studio Code - Insiders.app/Contents/MacOS/Electron':
'code-insiders',
'/Applications/VSCodium.app/Contents/MacOS/Electron': 'vscodium',
'/Applications/AppCode.app/Contents/MacOS/appcode':
'/Applications/AppCode.app/Contents/MacOS/appcode',
'/Applications/CLion.app/Contents/MacOS/clion':
'/Applications/CLion.app/Contents/MacOS/clion',
'/Applications/IntelliJ IDEA.app/Contents/MacOS/idea':
'/Applications/IntelliJ IDEA.app/Contents/MacOS/idea',
'/Applications/PhpStorm.app/Contents/MacOS/phpstorm':
'/Applications/PhpStorm.app/Contents/MacOS/phpstorm',
'/Applications/PyCharm.app/Contents/MacOS/pycharm':
'/Applications/PyCharm.app/Contents/MacOS/pycharm',
'/Applications/PyCharm CE.app/Contents/MacOS/pycharm':
'/Applications/PyCharm CE.app/Contents/MacOS/pycharm',
'/Applications/RubyMine.app/Contents/MacOS/rubymine':
'/Applications/RubyMine.app/Contents/MacOS/rubymine',
'/Applications/WebStorm.app/Contents/MacOS/webstorm':
'/Applications/WebStorm.app/Contents/MacOS/webstorm',
'/Applications/MacVim.app/Contents/MacOS/MacVim': 'mvim',
'/Applications/GoLand.app/Contents/MacOS/goland':
'/Applications/GoLand.app/Contents/MacOS/goland',
'/Applications/Rider.app/Contents/MacOS/rider':
'/Applications/Rider.app/Contents/MacOS/rider',
};
const COMMON_EDITORS_LINUX = {
atom: 'atom',
Brackets: 'brackets',
code: 'code',
'code-insiders': 'code-insiders',
vscodium: 'vscodium',
emacs: 'emacs',
gvim: 'gvim',
'idea.sh': 'idea',
'phpstorm.sh': 'phpstorm',
'pycharm.sh': 'pycharm',
'rubymine.sh': 'rubymine',
sublime_text: 'sublime_text',
vim: 'vim',
'webstorm.sh': 'webstorm',
'goland.sh': 'goland',
'rider.sh': 'rider',
};
const COMMON_EDITORS_WIN = [
'Brackets.exe',
'Code.exe',
'Code - Insiders.exe',
'VSCodium.exe',
'atom.exe',
'sublime_text.exe',
'notepad++.exe',
'clion.exe',
'clion64.exe',
'idea.exe',
'idea64.exe',
'phpstorm.exe',
'phpstorm64.exe',
'pycharm.exe',
'pycharm64.exe',
'rubymine.exe',
'rubymine64.exe',
'webstorm.exe',
'webstorm64.exe',
'goland.exe',
'goland64.exe',
'rider.exe',
'rider64.exe',
];
// Transpiled version of: /^([A-Za-z]:[/\\])?[\p{L}0-9/.\-_\\]+$/u
// Non-transpiled version requires support for Unicode property regex. Allows
// alphanumeric characters, periods, dashes, slashes, and underscores.
const WINDOWS_FILE_NAME_WHITELIST =
/^([A-Za-z]:[/\\])?(?:[\x2D-9A-Z\\_a-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16F1-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1878\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEF\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA7B9\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA8FE\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF40\uDF42-\uDF49\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE35\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2\uDD00-\uDD23\uDF00-\uDF1C\uDF27\uDF30-\uDF45]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD44\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF1A]|\uD806[\uDC00-\uDC2B\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDE9D\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46\uDD60-\uDD65\uDD67\uDD68\uDD6A-\uDD89\uDD98\uDEE0-\uDEF2]|\uD808[\uDC00-\uDF99]|\uD809[\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDE40-\uDE7F\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFF1]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D])+$/;
function addWorkspaceToArgumentsIfExists(args, workspace) {
if (workspace) {
args.unshift(workspace);
}
return args;
}
function getArgumentsForLineNumber(
editor,
fileName,
lineNumber,
colNumber,
workspace
) {
const editorBasename = path.basename(editor).replace(/\.(exe|cmd|bat)$/i, '');
switch (editorBasename) {
case 'atom':
case 'Atom':
case 'Atom Beta':
case 'subl':
case 'sublime':
case 'sublime_text':
return [fileName + ':' + lineNumber + ':' + colNumber];
case 'wstorm':
case 'charm':
return [fileName + ':' + lineNumber];
case 'notepad++':
return ['-n' + lineNumber, '-c' + colNumber, fileName];
case 'vim':
case 'mvim':
case 'joe':
case 'gvim':
return ['+' + lineNumber, fileName];
case 'emacs':
case 'emacsclient':
return ['+' + lineNumber + ':' + colNumber, fileName];
case 'rmate':
case 'mate':
case 'mine':
return ['--line', lineNumber, fileName];
case 'code':
case 'Code':
case 'code-insiders':
case 'Code - Insiders':
case 'vscodium':
case 'VSCodium':
return addWorkspaceToArgumentsIfExists(
['-g', fileName + ':' + lineNumber + ':' + colNumber],
workspace
);
case 'appcode':
case 'clion':
case 'clion64':
case 'idea':
case 'idea64':
case 'phpstorm':
case 'phpstorm64':
case 'pycharm':
case 'pycharm64':
case 'rubymine':
case 'rubymine64':
case 'webstorm':
case 'webstorm64':
case 'goland':
case 'goland64':
case 'rider':
case 'rider64':
return addWorkspaceToArgumentsIfExists(
['--line', lineNumber, fileName],
workspace
);
}
// For all others, drop the lineNumber until we have
// a mapping above, since providing the lineNumber incorrectly
// can result in errors or confusing behavior.
return [fileName];
}
function guessEditor() {
// Explicit config always wins
if (process.env.REACT_EDITOR) {
return shellQuote.parse(process.env.REACT_EDITOR);
}
// We can find out which editor is currently running by:
// `ps x` on macOS and Linux
// `Get-Process` on Windows
try {
if (process.platform === 'darwin') {
const output = child_process.execSync('ps x').toString();
const processNames = Object.keys(COMMON_EDITORS_OSX);
for (let i = 0; i < processNames.length; i++) {
const processName = processNames[i];
if (output.indexOf(processName) !== -1) {
return [COMMON_EDITORS_OSX[processName]];
}
}
} else if (process.platform === 'win32') {
// Some processes need elevated rights to get its executable path.
// Just filter them out upfront. This also saves 10-20ms on the command.
const output = child_process
.execSync(
'wmic process where "executablepath is not null" get executablepath'
)
.toString();
const runningProcesses = output.split('\r\n');
for (let i = 0; i < runningProcesses.length; i++) {
const processPath = runningProcesses[i].trim();
const processName = path.basename(processPath);
if (COMMON_EDITORS_WIN.indexOf(processName) !== -1) {
return [processPath];
}
}
} else if (process.platform === 'linux') {
// --no-heading No header line
// x List all processes owned by you
// -o comm Need only names column
const output = child_process
.execSync('ps x --no-heading -o comm --sort=comm')
.toString();
const processNames = Object.keys(COMMON_EDITORS_LINUX);
for (let i = 0; i < processNames.length; i++) {
const processName = processNames[i];
if (output.indexOf(processName) !== -1) {
return [COMMON_EDITORS_LINUX[processName]];
}
}
}
} catch (error) {
// Ignore...
}
// Last resort, use old skool env vars
if (process.env.VISUAL) {
return [process.env.VISUAL];
} else if (process.env.EDITOR) {
return [process.env.EDITOR];
}
return [null];
}
function printInstructions(fileName, errorMessage) {
console.log();
console.log(
chalk.red('Could not open ' + path.basename(fileName) + ' in the editor.')
);
if (errorMessage) {
if (errorMessage[errorMessage.length - 1] !== '.') {
errorMessage += '.';
}
console.log(
chalk.red('The editor process exited with an error: ' + errorMessage)
);
}
console.log();
console.log(
'To set up the editor integration, add something like ' +
chalk.cyan('REACT_EDITOR=atom') +
' to the ' +
chalk.green('.env.local') +
' file in your project folder ' +
'and restart the development server. Learn more: ' +
chalk.green('https://goo.gl/MMTaZt')
);
console.log();
}
let _childProcess = null;
function launchEditor(fileName, lineNumber, colNumber) {
if (!fs.existsSync(fileName)) {
return;
}
// Sanitize lineNumber to prevent malicious use on win32
// via: https://github.com/nodejs/node/blob/c3bb4b1aa5e907d489619fb43d233c3336bfc03d/lib/child_process.js#L333
// and it should be a positive integer
if (!(Number.isInteger(lineNumber) && lineNumber > 0)) {
return;
}
// colNumber is optional, but should be a positive integer too
// default is 1
if (!(Number.isInteger(colNumber) && colNumber > 0)) {
colNumber = 1;
}
let [editor, ...args] = guessEditor();
if (!editor) {
printInstructions(fileName, null);
return;
}
if (editor.toLowerCase() === 'none') {
return;
}
if (
process.platform === 'linux' &&
fileName.startsWith('/mnt/') &&
/Microsoft/i.test(os.release())
) {
// Assume WSL / "Bash on Ubuntu on Windows" is being used, and
// that the file exists on the Windows file system.
// `os.release()` is "4.4.0-43-Microsoft" in the current release
// build of WSL, see: https://github.com/Microsoft/BashOnWindows/issues/423#issuecomment-221627364
// When a Windows editor is specified, interop functionality can
// handle the path translation, but only if a relative path is used.
fileName = path.relative('', fileName);
}
// cmd.exe on Windows is vulnerable to RCE attacks given a file name of the
// form "C:\Users\myusername\Downloads\& curl 172.21.93.52". Use a whitelist
// to validate user-provided file names. This doesn't cover the entire range
// of valid file names but should cover almost all of them in practice.
if (
process.platform === 'win32' &&
!WINDOWS_FILE_NAME_WHITELIST.test(fileName.trim())
) {
console.log();
console.log(
chalk.red('Could not open ' + path.basename(fileName) + ' in the editor.')
);
console.log();
console.log(
'When running on Windows, file names are checked against a whitelist ' +
'to protect against remote code execution attacks. File names may ' +
'consist only of alphanumeric characters (all languages), periods, ' +
'dashes, slashes, and underscores.'
);
console.log();
return;
}
let workspace = null;
if (lineNumber) {
args = args.concat(
getArgumentsForLineNumber(
editor,
fileName,
lineNumber,
colNumber,
workspace
)
);
} else {
args.push(fileName);
}
if (_childProcess && isTerminalEditor(editor)) {
// There's an existing editor process already and it's attached
// to the terminal, so go kill it. Otherwise two separate editor
// instances attach to the stdin/stdout which gets confusing.
_childProcess.kill('SIGKILL');
}
if (process.platform === 'win32') {
// On Windows, launch the editor in a shell because spawn can only
// launch .exe files.
_childProcess = child_process.spawn(
'cmd.exe',
['/C', editor].concat(args),
{ stdio: 'inherit' }
);
} else {
_childProcess = child_process.spawn(editor, args, { stdio: 'inherit' });
}
_childProcess.on('exit', function (errorCode) {
_childProcess = null;
if (errorCode) {
printInstructions(fileName, '(code ' + errorCode + ')');
}
});
_childProcess.on('error', function (error) {
printInstructions(fileName, error.message);
});
}
module.exports = launchEditor;
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-dev-utils/ForkTsCheckerWarningWebpackPlugin.js | packages/react-dev-utils/ForkTsCheckerWarningWebpackPlugin.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
// References:
// - https://github.com/TypeStrong/fork-ts-checker-webpack-plugin#plugin-hooks
// - https://github.com/TypeStrong/fork-ts-checker-webpack-plugin/issues/232#issuecomment-645543747
const ForkTsCheckerWebpackPlugin = require('./ForkTsCheckerWebpackPlugin');
module.exports = class ForkTsCheckerWarningWebpackPlugin {
apply(compiler) {
new ForkTsCheckerWebpackPlugin().apply(compiler);
const hooks = ForkTsCheckerWebpackPlugin.getCompilerHooks(compiler);
hooks.issues.tap('ForkTsCheckerWarningWebpackPlugin', issues =>
issues.map(issue => ({ ...issue, severity: 'warning' }))
);
}
};
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-dev-utils/formatWebpackMessages.js | packages/react-dev-utils/formatWebpackMessages.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
const friendlySyntaxErrorLabel = 'Syntax error:';
function isLikelyASyntaxError(message) {
return message.indexOf(friendlySyntaxErrorLabel) !== -1;
}
// Cleans up webpack error messages.
function formatMessage(message) {
let lines = [];
if (typeof message === 'string') {
lines = message.split('\n');
} else if ('message' in message) {
lines = message['message'].split('\n');
} else if (Array.isArray(message)) {
message.forEach(message => {
if ('message' in message) {
lines = message['message'].split('\n');
}
});
}
// Strip webpack-added headers off errors/warnings
// https://github.com/webpack/webpack/blob/master/lib/ModuleError.js
lines = lines.filter(line => !/Module [A-z ]+\(from/.test(line));
// Transform parsing error into syntax error
// TODO: move this to our ESLint formatter?
lines = lines.map(line => {
const parsingError = /Line (\d+):(?:(\d+):)?\s*Parsing error: (.+)$/.exec(
line
);
if (!parsingError) {
return line;
}
const [, errorLine, errorColumn, errorMessage] = parsingError;
return `${friendlySyntaxErrorLabel} ${errorMessage} (${errorLine}:${errorColumn})`;
});
message = lines.join('\n');
// Smoosh syntax errors (commonly found in CSS)
message = message.replace(
/SyntaxError\s+\((\d+):(\d+)\)\s*(.+?)\n/g,
`${friendlySyntaxErrorLabel} $3 ($1:$2)\n`
);
// Clean up export errors
message = message.replace(
/^.*export '(.+?)' was not found in '(.+?)'.*$/gm,
`Attempted import error: '$1' is not exported from '$2'.`
);
message = message.replace(
/^.*export 'default' \(imported as '(.+?)'\) was not found in '(.+?)'.*$/gm,
`Attempted import error: '$2' does not contain a default export (imported as '$1').`
);
message = message.replace(
/^.*export '(.+?)' \(imported as '(.+?)'\) was not found in '(.+?)'.*$/gm,
`Attempted import error: '$1' is not exported from '$3' (imported as '$2').`
);
lines = message.split('\n');
// Remove leading newline
if (lines.length > 2 && lines[1].trim() === '') {
lines.splice(1, 1);
}
// Clean up file name
lines[0] = lines[0].replace(/^(.*) \d+:\d+-\d+$/, '$1');
// Cleans up verbose "module not found" messages for files and packages.
if (lines[1] && lines[1].indexOf('Module not found: ') === 0) {
lines = [
lines[0],
lines[1]
.replace('Error: ', '')
.replace('Module not found: Cannot find file:', 'Cannot find file:'),
];
}
// Add helpful message for users trying to use Sass for the first time
if (lines[1] && lines[1].match(/Cannot find module.+sass/)) {
lines[1] = 'To import Sass files, you first need to install sass.\n';
lines[1] +=
'Run `npm install sass` or `yarn add sass` inside your workspace.';
}
message = lines.join('\n');
// Internal stacks are generally useless so we strip them... with the
// exception of stacks containing `webpack:` because they're normally
// from user code generated by webpack. For more information see
// https://github.com/facebook/create-react-app/pull/1050
message = message.replace(
/^\s*at\s((?!webpack:).)*:\d+:\d+[\s)]*(\n|$)/gm,
''
); // at ... ...:x:y
message = message.replace(/^\s*at\s<anonymous>(\n|$)/gm, ''); // at <anonymous>
lines = message.split('\n');
// Remove duplicated newlines
lines = lines.filter(
(line, index, arr) =>
index === 0 || line.trim() !== '' || line.trim() !== arr[index - 1].trim()
);
// Reassemble the message
message = lines.join('\n');
return message.trim();
}
function formatWebpackMessages(json) {
const formattedErrors = json.errors.map(formatMessage);
const formattedWarnings = json.warnings.map(formatMessage);
const result = { errors: formattedErrors, warnings: formattedWarnings };
if (result.errors.some(isLikelyASyntaxError)) {
// If there are any syntax errors, show just them.
result.errors = result.errors.filter(isLikelyASyntaxError);
}
return result;
}
module.exports = formatWebpackMessages;
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-dev-utils/getPublicUrlOrPath.js | packages/react-dev-utils/getPublicUrlOrPath.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
const { URL } = require('url');
module.exports = getPublicUrlOrPath;
/**
* Returns a URL or a path with slash at the end
* In production can be URL, abolute path, relative path
* In development always will be an absolute path
* In development can use `path` module functions for operations
*
* @param {boolean} isEnvDevelopment
* @param {(string|undefined)} homepage a valid url or pathname
* @param {(string|undefined)} envPublicUrl a valid url or pathname
* @returns {string}
*/
function getPublicUrlOrPath(isEnvDevelopment, homepage, envPublicUrl) {
const stubDomain = 'https://create-react-app.dev';
if (envPublicUrl) {
// ensure last slash exists
envPublicUrl = envPublicUrl.endsWith('/')
? envPublicUrl
: envPublicUrl + '/';
// validate if `envPublicUrl` is a URL or path like
// `stubDomain` is ignored if `envPublicUrl` contains a domain
const validPublicUrl = new URL(envPublicUrl, stubDomain);
return isEnvDevelopment
? envPublicUrl.startsWith('.')
? '/'
: validPublicUrl.pathname
: // Some apps do not use client-side routing with pushState.
// For these, "homepage" can be set to "." to enable relative asset paths.
envPublicUrl;
}
if (homepage) {
// strip last slash if exists
homepage = homepage.endsWith('/') ? homepage : homepage + '/';
// validate if `homepage` is a URL or path like and use just pathname
const validHomepagePathname = new URL(homepage, stubDomain).pathname;
return isEnvDevelopment
? homepage.startsWith('.')
? '/'
: validHomepagePathname
: // Some apps do not use client-side routing with pushState.
// For these, "homepage" can be set to "." to enable relative asset paths.
homepage.startsWith('.')
? homepage
: validHomepagePathname;
}
return '/';
}
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-dev-utils/launchEditorEndpoint.js | packages/react-dev-utils/launchEditorEndpoint.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
// TODO: we might want to make this injectable to support DEV-time non-root URLs.
module.exports = '/__open-stack-frame-in-editor';
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-dev-utils/WebpackDevServerUtils.js | packages/react-dev-utils/WebpackDevServerUtils.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
const address = require('address');
const fs = require('fs');
const path = require('path');
const url = require('url');
const chalk = require('chalk');
const detect = require('detect-port-alt');
const isRoot = require('is-root');
const prompts = require('prompts');
const clearConsole = require('./clearConsole');
const formatWebpackMessages = require('./formatWebpackMessages');
const getProcessForPort = require('./getProcessForPort');
const forkTsCheckerWebpackPlugin = require('./ForkTsCheckerWebpackPlugin');
const isInteractive = process.stdout.isTTY;
function prepareUrls(protocol, host, port, pathname = '/') {
const formatUrl = hostname =>
url.format({
protocol,
hostname,
port,
pathname,
});
const prettyPrintUrl = hostname =>
url.format({
protocol,
hostname,
port: chalk.bold(port),
pathname,
});
const isUnspecifiedHost = host === '0.0.0.0' || host === '::';
let prettyHost, lanUrlForConfig, lanUrlForTerminal;
if (isUnspecifiedHost) {
prettyHost = 'localhost';
try {
// This can only return an IPv4 address
lanUrlForConfig = address.ip();
if (lanUrlForConfig) {
// Check if the address is a private ip
// https://en.wikipedia.org/wiki/Private_network#Private_IPv4_address_spaces
if (
/^10[.]|^172[.](1[6-9]|2[0-9]|3[0-1])[.]|^192[.]168[.]/.test(
lanUrlForConfig
)
) {
// Address is private, format it for later use
lanUrlForTerminal = prettyPrintUrl(lanUrlForConfig);
} else {
// Address is not private, so we will discard it
lanUrlForConfig = undefined;
}
}
} catch (_e) {
// ignored
}
} else {
prettyHost = host;
}
const localUrlForTerminal = prettyPrintUrl(prettyHost);
const localUrlForBrowser = formatUrl(prettyHost);
return {
lanUrlForConfig,
lanUrlForTerminal,
localUrlForTerminal,
localUrlForBrowser,
};
}
function printInstructions(appName, urls, useYarn) {
console.log();
console.log(`You can now view ${chalk.bold(appName)} in the browser.`);
console.log();
if (urls.lanUrlForTerminal) {
console.log(
` ${chalk.bold('Local:')} ${urls.localUrlForTerminal}`
);
console.log(
` ${chalk.bold('On Your Network:')} ${urls.lanUrlForTerminal}`
);
} else {
console.log(` ${urls.localUrlForTerminal}`);
}
console.log();
console.log('Note that the development build is not optimized.');
console.log(
`To create a production build, use ` +
`${chalk.cyan(`${useYarn ? 'yarn' : 'npm run'} build`)}.`
);
console.log();
}
function createCompiler({
appName,
config,
urls,
useYarn,
useTypeScript,
webpack,
}) {
// "Compiler" is a low-level interface to webpack.
// It lets us listen to some events and provide our own custom messages.
let compiler;
try {
compiler = webpack(config);
} catch (err) {
console.log(chalk.red('Failed to compile.'));
console.log();
console.log(err.message || err);
console.log();
process.exit(1);
}
// "invalid" event fires when you have changed a file, and webpack is
// recompiling a bundle. WebpackDevServer takes care to pause serving the
// bundle, so if you refresh, it'll wait instead of serving the old one.
// "invalid" is short for "bundle invalidated", it doesn't imply any errors.
compiler.hooks.invalid.tap('invalid', () => {
if (isInteractive) {
clearConsole();
}
console.log('Compiling...');
});
let isFirstCompile = true;
let tsMessagesPromise;
if (useTypeScript) {
forkTsCheckerWebpackPlugin
.getCompilerHooks(compiler)
.waiting.tap('awaitingTypeScriptCheck', () => {
console.log(
chalk.yellow(
'Files successfully emitted, waiting for typecheck results...'
)
);
});
}
// "done" event fires when webpack has finished recompiling the bundle.
// Whether or not you have warnings or errors, you will get this event.
compiler.hooks.done.tap('done', async stats => {
if (isInteractive) {
clearConsole();
}
// We have switched off the default webpack output in WebpackDevServer
// options so we are going to "massage" the warnings and errors and present
// them in a readable focused way.
// We only construct the warnings and errors for speed:
// https://github.com/facebook/create-react-app/issues/4492#issuecomment-421959548
const statsData = stats.toJson({
all: false,
warnings: true,
errors: true,
});
const messages = formatWebpackMessages(statsData);
const isSuccessful = !messages.errors.length && !messages.warnings.length;
if (isSuccessful) {
console.log(chalk.green('Compiled successfully!'));
}
if (isSuccessful && (isInteractive || isFirstCompile)) {
printInstructions(appName, urls, useYarn);
}
isFirstCompile = false;
// If errors exist, only show errors.
if (messages.errors.length) {
// Only keep the first error. Others are often indicative
// of the same problem, but confuse the reader with noise.
if (messages.errors.length > 1) {
messages.errors.length = 1;
}
console.log(chalk.red('Failed to compile.\n'));
console.log(messages.errors.join('\n\n'));
return;
}
// Show warnings if no errors were found.
if (messages.warnings.length) {
console.log(chalk.yellow('Compiled with warnings.\n'));
console.log(messages.warnings.join('\n\n'));
// Teach some ESLint tricks.
console.log(
'\nSearch for the ' +
chalk.underline(chalk.yellow('keywords')) +
' to learn more about each warning.'
);
console.log(
'To ignore, add ' +
chalk.cyan('// eslint-disable-next-line') +
' to the line before.\n'
);
}
});
// You can safely remove this after ejecting.
// We only use this block for testing of Create React App itself:
const isSmokeTest = process.argv.some(
arg => arg.indexOf('--smoke-test') > -1
);
if (isSmokeTest) {
compiler.hooks.failed.tap('smokeTest', async () => {
await tsMessagesPromise;
process.exit(1);
});
compiler.hooks.done.tap('smokeTest', async stats => {
await tsMessagesPromise;
if (stats.hasErrors() || stats.hasWarnings()) {
process.exit(1);
} else {
process.exit(0);
}
});
}
return compiler;
}
function resolveLoopback(proxy) {
const o = url.parse(proxy);
o.host = undefined;
if (o.hostname !== 'localhost') {
return proxy;
}
// Unfortunately, many languages (unlike node) do not yet support IPv6.
// This means even though localhost resolves to ::1, the application
// must fall back to IPv4 (on 127.0.0.1).
// We can re-enable this in a few years.
/*try {
o.hostname = address.ipv6() ? '::1' : '127.0.0.1';
} catch (_ignored) {
o.hostname = '127.0.0.1';
}*/
try {
// Check if we're on a network; if we are, chances are we can resolve
// localhost. Otherwise, we can just be safe and assume localhost is
// IPv4 for maximum compatibility.
if (!address.ip()) {
o.hostname = '127.0.0.1';
}
} catch (_ignored) {
o.hostname = '127.0.0.1';
}
return url.format(o);
}
// We need to provide a custom onError function for httpProxyMiddleware.
// It allows us to log custom error messages on the console.
function onProxyError(proxy) {
return (err, req, res) => {
const host = req.headers && req.headers.host;
console.log(
chalk.red('Proxy error:') +
' Could not proxy request ' +
chalk.cyan(req.url) +
' from ' +
chalk.cyan(host) +
' to ' +
chalk.cyan(proxy) +
'.'
);
console.log(
'See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (' +
chalk.cyan(err.code) +
').'
);
console.log();
// And immediately send the proper error response to the client.
// Otherwise, the request will eventually timeout with ERR_EMPTY_RESPONSE on the client side.
if (res.writeHead && !res.headersSent) {
res.writeHead(500);
}
res.end(
'Proxy error: Could not proxy request ' +
req.url +
' from ' +
host +
' to ' +
proxy +
' (' +
err.code +
').'
);
};
}
function prepareProxy(proxy, appPublicFolder, servedPathname) {
// `proxy` lets you specify alternate servers for specific requests.
if (!proxy) {
return undefined;
}
if (typeof proxy !== 'string') {
console.log(
chalk.red('When specified, "proxy" in package.json must be a string.')
);
console.log(
chalk.red('Instead, the type of "proxy" was "' + typeof proxy + '".')
);
console.log(
chalk.red('Either remove "proxy" from package.json, or make it a string.')
);
process.exit(1);
}
// If proxy is specified, let it handle any request except for
// files in the public folder and requests to the WebpackDevServer socket endpoint.
// https://github.com/facebook/create-react-app/issues/6720
const sockPath = process.env.WDS_SOCKET_PATH || '/ws';
const isDefaultSockHost = !process.env.WDS_SOCKET_HOST;
function mayProxy(pathname) {
const maybePublicPath = path.resolve(
appPublicFolder,
pathname.replace(new RegExp('^' + servedPathname), '')
);
const isPublicFileRequest = fs.existsSync(maybePublicPath);
// used by webpackHotDevClient
const isWdsEndpointRequest =
isDefaultSockHost && pathname.startsWith(sockPath);
return !(isPublicFileRequest || isWdsEndpointRequest);
}
if (!/^http(s)?:\/\//.test(proxy)) {
console.log(
chalk.red(
'When "proxy" is specified in package.json it must start with either http:// or https://'
)
);
process.exit(1);
}
let target;
if (process.platform === 'win32') {
target = resolveLoopback(proxy);
} else {
target = proxy;
}
return [
{
target,
logLevel: 'silent',
// For single page apps, we generally want to fallback to /index.html.
// However we also want to respect `proxy` for API calls.
// So if `proxy` is specified as a string, we need to decide which fallback to use.
// We use a heuristic: We want to proxy all the requests that are not meant
// for static assets and as all the requests for static assets will be using
// `GET` method, we can proxy all non-`GET` requests.
// For `GET` requests, if request `accept`s text/html, we pick /index.html.
// Modern browsers include text/html into `accept` header when navigating.
// However API calls like `fetch()` won’t generally accept text/html.
// If this heuristic doesn’t work well for you, use `src/setupProxy.js`.
context: function (pathname, req) {
return (
req.method !== 'GET' ||
(mayProxy(pathname) &&
req.headers.accept &&
req.headers.accept.indexOf('text/html') === -1)
);
},
onProxyReq: proxyReq => {
// Browsers may send Origin headers even with same-origin
// requests. To prevent CORS issues, we have to change
// the Origin to match the target URL.
if (proxyReq.getHeader('origin')) {
proxyReq.setHeader('origin', target);
}
},
onError: onProxyError(target),
secure: false,
changeOrigin: true,
ws: true,
xfwd: true,
},
];
}
function choosePort(host, defaultPort) {
return detect(defaultPort, host).then(
port =>
new Promise(resolve => {
if (port === defaultPort) {
return resolve(port);
}
const message =
process.platform !== 'win32' && defaultPort < 1024 && !isRoot()
? `Admin permissions are required to run a server on a port below 1024.`
: `Something is already running on port ${defaultPort}.`;
if (isInteractive) {
clearConsole();
const existingProcess = getProcessForPort(defaultPort);
const question = {
type: 'confirm',
name: 'shouldChangePort',
message:
chalk.yellow(
message +
`${existingProcess ? ` Probably:\n ${existingProcess}` : ''}`
) + '\n\nWould you like to run the app on another port instead?',
initial: true,
};
prompts(question).then(answer => {
if (answer.shouldChangePort) {
resolve(port);
} else {
resolve(null);
}
});
} else {
console.log(chalk.red(message));
resolve(null);
}
}),
err => {
throw new Error(
chalk.red(`Could not find an open port at ${chalk.bold(host)}.`) +
'\n' +
('Network error message: ' + err.message || err) +
'\n'
);
}
);
}
module.exports = {
choosePort,
createCompiler,
prepareProxy,
prepareUrls,
};
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-dev-utils/getCSSModuleLocalIdent.js | packages/react-dev-utils/getCSSModuleLocalIdent.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
const loaderUtils = require('loader-utils');
const path = require('path');
module.exports = function getLocalIdent(
context,
localIdentName,
localName,
options
) {
// Use the filename or folder name, based on some uses the index.js / index.module.(css|scss|sass) project style
const fileNameOrFolder = context.resourcePath.match(
/index\.module\.(css|scss|sass)$/
)
? '[folder]'
: '[name]';
// Create a hash based on a the file location and class name. Will be unique across a project, and close to globally unique.
const hash = loaderUtils.getHashDigest(
path.posix.relative(context.rootContext, context.resourcePath) + localName,
'md5',
'base64',
5
);
// Use loaderUtils to find the file or folder name
const className = loaderUtils.interpolateName(
context,
fileNameOrFolder + '_' + localName + '__' + hash,
options
);
// Remove the .module that appears in every classname when based on the file and replace all "." with "_".
return className.replace('.module_', '_').replace(/\./g, '_');
};
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-dev-utils/chalk.js | packages/react-dev-utils/chalk.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
var chalk = require('chalk');
module.exports = chalk;
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-dev-utils/checkRequiredFiles.js | packages/react-dev-utils/checkRequiredFiles.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
var fs = require('fs');
var path = require('path');
var chalk = require('chalk');
function checkRequiredFiles(files) {
var currentFilePath;
try {
files.forEach(filePath => {
currentFilePath = filePath;
fs.accessSync(filePath, fs.F_OK);
});
return true;
} catch (err) {
var dirName = path.dirname(currentFilePath);
var fileName = path.basename(currentFilePath);
console.log(chalk.red('Could not find a required file.'));
console.log(chalk.red(' Name: ') + chalk.cyan(fileName));
console.log(chalk.red(' Searched in: ') + chalk.cyan(dirName));
return false;
}
}
module.exports = checkRequiredFiles;
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-dev-utils/redirectServedPathMiddleware.js | packages/react-dev-utils/redirectServedPathMiddleware.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
const path = require('path');
module.exports = function createRedirectServedPathMiddleware(servedPath) {
// remove end slash so user can land on `/test` instead of `/test/`
servedPath = servedPath.slice(0, -1);
return function redirectServedPathMiddleware(req, res, next) {
if (
servedPath === '' ||
req.url === servedPath ||
req.url.startsWith(servedPath)
) {
next();
} else {
const newPath = path.posix.join(
servedPath,
req.path !== '/' ? req.path : ''
);
res.redirect(newPath);
}
};
};
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-dev-utils/ModuleScopePlugin.js | packages/react-dev-utils/ModuleScopePlugin.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
const chalk = require('chalk');
const path = require('path');
const os = require('os');
class ModuleScopePlugin {
constructor(appSrc, allowedFiles = []) {
this.appSrcs = Array.isArray(appSrc) ? appSrc : [appSrc];
this.allowedFiles = new Set(allowedFiles);
this.allowedPaths = [...allowedFiles]
.map(path.dirname)
.filter(p => path.relative(p, process.cwd()) !== '');
}
apply(resolver) {
const { appSrcs } = this;
resolver.hooks.file.tapAsync(
'ModuleScopePlugin',
(request, contextResolver, callback) => {
// Unknown issuer, probably webpack internals
if (!request.context.issuer) {
return callback();
}
if (
// If this resolves to a node_module, we don't care what happens next
request.descriptionFileRoot.indexOf('/node_modules/') !== -1 ||
request.descriptionFileRoot.indexOf('\\node_modules\\') !== -1 ||
// Make sure this request was manual
!request.__innerRequest_request
) {
return callback();
}
// Resolve the issuer from our appSrc and make sure it's one of our files
// Maybe an indexOf === 0 would be better?
if (
appSrcs.every(appSrc => {
const relative = path.relative(appSrc, request.context.issuer);
// If it's not in one of our app src or a subdirectory, not our request!
return relative.startsWith('../') || relative.startsWith('..\\');
})
) {
return callback();
}
const requestFullPath = path.resolve(
path.dirname(request.context.issuer),
request.__innerRequest_request
);
if (this.allowedFiles.has(requestFullPath)) {
return callback();
}
if (
this.allowedPaths.some(allowedFile => {
return requestFullPath.startsWith(allowedFile);
})
) {
return callback();
}
// Find path from src to the requested file
// Error if in a parent directory of all given appSrcs
if (
appSrcs.every(appSrc => {
const requestRelative = path.relative(appSrc, requestFullPath);
return (
requestRelative.startsWith('../') ||
requestRelative.startsWith('..\\')
);
})
) {
const scopeError = new Error(
`You attempted to import ${chalk.cyan(
request.__innerRequest_request
)} which falls outside of the project ${chalk.cyan(
'src/'
)} directory. ` +
`Relative imports outside of ${chalk.cyan(
'src/'
)} are not supported.` +
os.EOL +
`You can either move it inside ${chalk.cyan(
'src/'
)}, or add a symlink to it from project's ${chalk.cyan(
'node_modules/'
)}.`
);
Object.defineProperty(scopeError, '__module_scope_plugin', {
value: true,
writable: false,
enumerable: false,
});
callback(scopeError, request);
} else {
callback();
}
}
);
}
}
module.exports = ModuleScopePlugin;
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-dev-utils/eslintFormatter.js | packages/react-dev-utils/eslintFormatter.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
const path = require('path');
const chalk = require('chalk');
const stripAnsi = require('strip-ansi');
const table = require('text-table');
const cwd = process.cwd();
const emitErrorsAsWarnings =
process.env.NODE_ENV === 'development' &&
process.env.ESLINT_NO_DEV_ERRORS === 'true';
function isError(message) {
if (message.fatal || message.severity === 2) {
return true;
}
return false;
}
function getRelativePath(filePath) {
return path.relative(cwd, filePath);
}
function formatter(results) {
let output = '\n';
let hasErrors = false;
let reportContainsErrorRuleIDs = false;
results.forEach(result => {
let messages = result.messages;
if (messages.length === 0) {
return;
}
messages = messages.map(message => {
let messageType;
if (isError(message) && !emitErrorsAsWarnings) {
messageType = 'error';
hasErrors = true;
if (message.ruleId) {
reportContainsErrorRuleIDs = true;
}
} else {
messageType = 'warn';
}
let line = message.line || 0;
if (message.column) {
line += ':' + message.column;
}
let position = chalk.bold('Line ' + line + ':');
return [
'',
position,
messageType,
message.message.replace(/\.$/, ''),
chalk.underline(message.ruleId || ''),
];
});
// if there are error messages, we want to show only errors
if (hasErrors) {
messages = messages.filter(m => m[2] === 'error');
}
// add color to rule keywords
messages.forEach(m => {
m[4] = m[2] === 'error' ? chalk.red(m[4]) : chalk.yellow(m[4]);
m.splice(2, 1);
});
let outputTable = table(messages, {
align: ['l', 'l', 'l'],
stringLength(str) {
return stripAnsi(str).length;
},
});
// print the filename and relative path
output += `${getRelativePath(result.filePath)}\n`;
// print the errors
output += `${outputTable}\n\n`;
});
if (reportContainsErrorRuleIDs) {
// Unlike with warnings, we have to do it here.
// We have similar code in react-scripts for warnings,
// but warnings can appear in multiple files so we only
// print it once at the end. For errors, however, we print
// it here because we always show at most one error, and
// we can only be sure it's an ESLint error before exiting
// this function.
output +=
'Search for the ' +
chalk.underline(chalk.red('keywords')) +
' to learn more about each error.';
}
return output;
}
module.exports = formatter;
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-dev-utils/InterpolateHtmlPlugin.js | packages/react-dev-utils/InterpolateHtmlPlugin.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
// This webpack plugin lets us interpolate custom variables into `index.html`.
// Usage: `new InterpolateHtmlPlugin(HtmlWebpackPlugin, { 'MY_VARIABLE': 42 })`
// Then, you can use %MY_VARIABLE% in your `index.html`.
// It works in tandem with HtmlWebpackPlugin.
// Learn more about creating plugins like this:
// https://github.com/ampedandwired/html-webpack-plugin#events
'use strict';
const escapeStringRegexp = require('escape-string-regexp');
class InterpolateHtmlPlugin {
constructor(htmlWebpackPlugin, replacements) {
this.htmlWebpackPlugin = htmlWebpackPlugin;
this.replacements = replacements;
}
apply(compiler) {
compiler.hooks.compilation.tap('InterpolateHtmlPlugin', compilation => {
this.htmlWebpackPlugin
.getHooks(compilation)
.afterTemplateExecution.tap('InterpolateHtmlPlugin', data => {
// Run HTML through a series of user-specified string replacements.
Object.keys(this.replacements).forEach(key => {
const value = this.replacements[key];
data.html = data.html.replace(
new RegExp('%' + escapeStringRegexp(key) + '%', 'g'),
value
);
});
});
});
}
}
module.exports = InterpolateHtmlPlugin;
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-dev-utils/openBrowser.js | packages/react-dev-utils/openBrowser.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
var chalk = require('chalk');
var execSync = require('child_process').execSync;
var spawn = require('cross-spawn');
var open = require('open');
// https://github.com/sindresorhus/open#app
var OSX_CHROME = 'google chrome';
const Actions = Object.freeze({
NONE: 0,
BROWSER: 1,
SCRIPT: 2,
});
function getBrowserEnv() {
// Attempt to honor this environment variable.
// It is specific to the operating system.
// See https://github.com/sindresorhus/open#app for documentation.
const value = process.env.BROWSER;
const args = process.env.BROWSER_ARGS
? process.env.BROWSER_ARGS.split(' ')
: [];
let action;
if (!value) {
// Default.
action = Actions.BROWSER;
} else if (value.toLowerCase().endsWith('.js')) {
action = Actions.SCRIPT;
} else if (value.toLowerCase() === 'none') {
action = Actions.NONE;
} else {
action = Actions.BROWSER;
}
return { action, value, args };
}
function executeNodeScript(scriptPath, url) {
const extraArgs = process.argv.slice(2);
const child = spawn(process.execPath, [scriptPath, ...extraArgs, url], {
stdio: 'inherit',
});
child.on('close', code => {
if (code !== 0) {
console.log();
console.log(
chalk.red(
'The script specified as BROWSER environment variable failed.'
)
);
console.log(chalk.cyan(scriptPath) + ' exited with code ' + code + '.');
console.log();
return;
}
});
return true;
}
function startBrowserProcess(browser, url, args) {
// If we're on OS X, the user hasn't specifically
// requested a different browser, we can try opening
// Chrome with AppleScript. This lets us reuse an
// existing tab when possible instead of creating a new one.
const shouldTryOpenChromiumWithAppleScript =
process.platform === 'darwin' &&
(typeof browser !== 'string' || browser === OSX_CHROME);
if (shouldTryOpenChromiumWithAppleScript) {
// Will use the first open browser found from list
const supportedChromiumBrowsers = [
'Google Chrome Canary',
'Google Chrome Dev',
'Google Chrome Beta',
'Google Chrome',
'Microsoft Edge',
'Brave Browser',
'Vivaldi',
'Chromium',
];
for (let chromiumBrowser of supportedChromiumBrowsers) {
try {
// Try our best to reuse existing tab
// on OSX Chromium-based browser with AppleScript
execSync('ps cax | grep "' + chromiumBrowser + '"');
execSync(
'osascript openChrome.applescript "' +
encodeURI(url) +
'" "' +
chromiumBrowser +
'"',
{
cwd: __dirname,
stdio: 'ignore',
}
);
return true;
} catch (err) {
// Ignore errors.
}
}
}
// Another special case: on OS X, check if BROWSER has been set to "open".
// In this case, instead of passing `open` to `opn` (which won't work),
// just ignore it (thus ensuring the intended behavior, i.e. opening the system browser):
// https://github.com/facebook/create-react-app/pull/1690#issuecomment-283518768
if (process.platform === 'darwin' && browser === 'open') {
browser = undefined;
}
// If there are arguments, they must be passed as array with the browser
if (typeof browser === 'string' && args.length > 0) {
browser = [browser].concat(args);
}
// Fallback to open
// (It will always open new tab)
try {
var options = { app: browser, wait: false, url: true };
open(url, options).catch(() => {}); // Prevent `unhandledRejection` error.
return true;
} catch (err) {
return false;
}
}
/**
* Reads the BROWSER environment variable and decides what to do with it. Returns
* true if it opened a browser or ran a node.js script, otherwise false.
*/
function openBrowser(url) {
const { action, value, args } = getBrowserEnv();
switch (action) {
case Actions.NONE:
// Special case: BROWSER="none" will prevent opening completely.
return false;
case Actions.SCRIPT:
return executeNodeScript(value, url);
case Actions.BROWSER:
return startBrowserProcess(value, url, args);
default:
throw new Error('Not implemented.');
}
}
module.exports = openBrowser;
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-dev-utils/printHostingInstructions.js | packages/react-dev-utils/printHostingInstructions.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
const chalk = require('chalk');
const url = require('url');
const globalModules = require('global-modules');
const fs = require('fs');
function printHostingInstructions(
appPackage,
publicUrl,
publicPath,
buildFolder,
useYarn
) {
if (publicUrl && publicUrl.includes('.github.io/')) {
// "homepage": "http://user.github.io/project"
const publicPathname = url.parse(publicPath).pathname;
const hasDeployScript =
typeof appPackage.scripts !== 'undefined' &&
typeof appPackage.scripts.deploy !== 'undefined';
printBaseMessage(buildFolder, publicPathname);
printDeployInstructions(publicUrl, hasDeployScript, useYarn);
} else if (publicPath !== '/') {
// "homepage": "http://mywebsite.com/project"
printBaseMessage(buildFolder, publicPath);
} else {
// "homepage": "http://mywebsite.com"
// or no homepage
printBaseMessage(buildFolder, publicUrl);
printStaticServerInstructions(buildFolder, useYarn);
}
console.log();
console.log('Find out more about deployment here:');
console.log();
console.log(` ${chalk.yellow('https://cra.link/deployment')}`);
console.log();
}
function printBaseMessage(buildFolder, hostingLocation) {
console.log(
`The project was built assuming it is hosted at ${chalk.green(
hostingLocation || 'the server root'
)}.`
);
console.log(
`You can control this with the ${chalk.green(
'homepage'
)} field in your ${chalk.cyan('package.json')}.`
);
if (!hostingLocation) {
console.log('For example, add this to build it for GitHub Pages:');
console.log();
console.log(
` ${chalk.green('"homepage"')} ${chalk.cyan(':')} ${chalk.green(
'"http://myname.github.io/myapp"'
)}${chalk.cyan(',')}`
);
}
console.log();
console.log(`The ${chalk.cyan(buildFolder)} folder is ready to be deployed.`);
}
function printDeployInstructions(publicUrl, hasDeployScript, useYarn) {
console.log(`To publish it at ${chalk.green(publicUrl)} , run:`);
console.log();
// If script deploy has been added to package.json, skip the instructions
if (!hasDeployScript) {
if (useYarn) {
console.log(` ${chalk.cyan('yarn')} add --dev gh-pages`);
} else {
console.log(` ${chalk.cyan('npm')} install --save-dev gh-pages`);
}
console.log();
console.log(
`Add the following script in your ${chalk.cyan('package.json')}.`
);
console.log();
console.log(` ${chalk.dim('// ...')}`);
console.log(` ${chalk.yellow('"scripts"')}: {`);
console.log(` ${chalk.dim('// ...')}`);
console.log(
` ${chalk.yellow('"predeploy"')}: ${chalk.yellow(
`"${useYarn ? 'yarn' : 'npm run'} build",`
)}`
);
console.log(
` ${chalk.yellow('"deploy"')}: ${chalk.yellow(
'"gh-pages -d build"'
)}`
);
console.log(' }');
console.log();
console.log('Then run:');
console.log();
}
console.log(` ${chalk.cyan(useYarn ? 'yarn' : 'npm')} run deploy`);
}
function printStaticServerInstructions(buildFolder, useYarn) {
console.log('You may serve it with a static server:');
console.log();
if (!fs.existsSync(`${globalModules}/serve`)) {
if (useYarn) {
console.log(` ${chalk.cyan('yarn')} global add serve`);
} else {
console.log(` ${chalk.cyan('npm')} install -g serve`);
}
}
console.log(` ${chalk.cyan('serve')} -s ${buildFolder}`);
}
module.exports = printHostingInstructions;
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-dev-utils/webpackHotDevClient.js | packages/react-dev-utils/webpackHotDevClient.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
// This alternative WebpackDevServer combines the functionality of:
// https://github.com/webpack/webpack-dev-server/blob/webpack-1/client/index.js
// https://github.com/webpack/webpack/blob/webpack-1/hot/dev-server.js
// It only supports their simplest configuration (hot updates on same server).
// It makes some opinionated choices on top, like adding a syntax error overlay
// that looks similar to our console output. The error overlay is inspired by:
// https://github.com/glenjamin/webpack-hot-middleware
var stripAnsi = require('strip-ansi');
var url = require('url');
var launchEditorEndpoint = require('./launchEditorEndpoint');
var formatWebpackMessages = require('./formatWebpackMessages');
var ErrorOverlay = require('react-error-overlay');
ErrorOverlay.setEditorHandler(function editorHandler(errorLocation) {
// Keep this sync with errorOverlayMiddleware.js
fetch(
launchEditorEndpoint +
'?fileName=' +
window.encodeURIComponent(errorLocation.fileName) +
'&lineNumber=' +
window.encodeURIComponent(errorLocation.lineNumber || 1) +
'&colNumber=' +
window.encodeURIComponent(errorLocation.colNumber || 1)
);
});
// We need to keep track of if there has been a runtime error.
// Essentially, we cannot guarantee application state was not corrupted by the
// runtime error. To prevent confusing behavior, we forcibly reload the entire
// application. This is handled below when we are notified of a compile (code
// change).
// See https://github.com/facebook/create-react-app/issues/3096
var hadRuntimeError = false;
ErrorOverlay.startReportingRuntimeErrors({
onError: function () {
hadRuntimeError = true;
},
filename: '/static/js/bundle.js',
});
if (module.hot && typeof module.hot.dispose === 'function') {
module.hot.dispose(function () {
// TODO: why do we need this?
ErrorOverlay.stopReportingRuntimeErrors();
});
}
// Connect to WebpackDevServer via a socket.
var connection = new WebSocket(
url.format({
protocol: window.location.protocol === 'https:' ? 'wss' : 'ws',
hostname: process.env.WDS_SOCKET_HOST || window.location.hostname,
port: process.env.WDS_SOCKET_PORT || window.location.port,
// Hardcoded in WebpackDevServer
pathname: process.env.WDS_SOCKET_PATH || '/ws',
slashes: true,
})
);
// Unlike WebpackDevServer client, we won't try to reconnect
// to avoid spamming the console. Disconnect usually happens
// when developer stops the server.
connection.onclose = function () {
if (typeof console !== 'undefined' && typeof console.info === 'function') {
console.info(
'The development server has disconnected.\nRefresh the page if necessary.'
);
}
};
// Remember some state related to hot module replacement.
var isFirstCompilation = true;
var mostRecentCompilationHash = null;
var hasCompileErrors = false;
function clearOutdatedErrors() {
// Clean up outdated compile errors, if any.
if (typeof console !== 'undefined' && typeof console.clear === 'function') {
if (hasCompileErrors) {
console.clear();
}
}
}
// Successful compilation.
function handleSuccess() {
clearOutdatedErrors();
var isHotUpdate = !isFirstCompilation;
isFirstCompilation = false;
hasCompileErrors = false;
// Attempt to apply hot updates or reload.
if (isHotUpdate) {
tryApplyUpdates(function onHotUpdateSuccess() {
// Only dismiss it when we're sure it's a hot update.
// Otherwise it would flicker right before the reload.
tryDismissErrorOverlay();
});
}
}
// Compilation with warnings (e.g. ESLint).
function handleWarnings(warnings) {
clearOutdatedErrors();
var isHotUpdate = !isFirstCompilation;
isFirstCompilation = false;
hasCompileErrors = false;
function printWarnings() {
// Print warnings to the console.
var formatted = formatWebpackMessages({
warnings: warnings,
errors: [],
});
if (typeof console !== 'undefined' && typeof console.warn === 'function') {
for (var i = 0; i < formatted.warnings.length; i++) {
if (i === 5) {
console.warn(
'There were more warnings in other files.\n' +
'You can find a complete log in the terminal.'
);
break;
}
console.warn(stripAnsi(formatted.warnings[i]));
}
}
}
printWarnings();
// Attempt to apply hot updates or reload.
if (isHotUpdate) {
tryApplyUpdates(function onSuccessfulHotUpdate() {
// Only dismiss it when we're sure it's a hot update.
// Otherwise it would flicker right before the reload.
tryDismissErrorOverlay();
});
}
}
// Compilation with errors (e.g. syntax error or missing modules).
function handleErrors(errors) {
clearOutdatedErrors();
isFirstCompilation = false;
hasCompileErrors = true;
// "Massage" webpack messages.
var formatted = formatWebpackMessages({
errors: errors,
warnings: [],
});
// Only show the first error.
ErrorOverlay.reportBuildError(formatted.errors[0]);
// Also log them to the console.
if (typeof console !== 'undefined' && typeof console.error === 'function') {
for (var i = 0; i < formatted.errors.length; i++) {
console.error(stripAnsi(formatted.errors[i]));
}
}
// Do not attempt to reload now.
// We will reload on next success instead.
}
function tryDismissErrorOverlay() {
if (!hasCompileErrors) {
ErrorOverlay.dismissBuildError();
}
}
// There is a newer version of the code available.
function handleAvailableHash(hash) {
// Update last known compilation hash.
mostRecentCompilationHash = hash;
}
// Handle messages from the server.
connection.onmessage = function (e) {
var message = JSON.parse(e.data);
switch (message.type) {
case 'hash':
handleAvailableHash(message.data);
break;
case 'still-ok':
case 'ok':
handleSuccess();
break;
case 'content-changed':
// Triggered when a file from `contentBase` changed.
window.location.reload();
break;
case 'warnings':
handleWarnings(message.data);
break;
case 'errors':
handleErrors(message.data);
break;
default:
// Do nothing.
}
};
// Is there a newer version of this code available?
function isUpdateAvailable() {
/* globals __webpack_hash__ */
// __webpack_hash__ is the hash of the current compilation.
// It's a global variable injected by webpack.
return mostRecentCompilationHash !== __webpack_hash__;
}
// webpack disallows updates in other states.
function canApplyUpdates() {
return module.hot.status() === 'idle';
}
function canAcceptErrors() {
// NOTE: This var is injected by Webpack's DefinePlugin, and is a boolean instead of string.
const hasReactRefresh = process.env.FAST_REFRESH;
const status = module.hot.status();
// React refresh can handle hot-reloading over errors.
// However, when hot-reload status is abort or fail,
// it indicates the current update cannot be applied safely,
// and thus we should bail out to a forced reload for consistency.
return hasReactRefresh && ['abort', 'fail'].indexOf(status) === -1;
}
// Attempt to update code on the fly, fall back to a hard reload.
function tryApplyUpdates(onHotUpdateSuccess) {
if (!module.hot) {
// HotModuleReplacementPlugin is not in webpack configuration.
window.location.reload();
return;
}
if (!isUpdateAvailable() || !canApplyUpdates()) {
return;
}
function handleApplyUpdates(err, updatedModules) {
const haveErrors = err || hadRuntimeError;
// When there is no error but updatedModules is unavailable,
// it indicates a critical failure in hot-reloading,
// e.g. server is not ready to serve new bundle,
// and hence we need to do a forced reload.
const needsForcedReload = !err && !updatedModules;
if ((haveErrors && !canAcceptErrors()) || needsForcedReload) {
window.location.reload();
return;
}
if (typeof onHotUpdateSuccess === 'function') {
// Maybe we want to do something.
onHotUpdateSuccess();
}
if (isUpdateAvailable()) {
// While we were updating, there was a new update! Do it again.
tryApplyUpdates();
}
}
// https://webpack.github.io/docs/hot-module-replacement.html#check
var result = module.hot.check(/* autoApply */ true, handleApplyUpdates);
// // webpack 2 returns a Promise instead of invoking a callback
if (result && result.then) {
result.then(
function (updatedModules) {
handleApplyUpdates(null, updatedModules);
},
function (err) {
handleApplyUpdates(err, null);
}
);
}
}
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-dev-utils/FileSizeReporter.js | packages/react-dev-utils/FileSizeReporter.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
var fs = require('fs');
var path = require('path');
var chalk = require('chalk');
var filesize = require('filesize');
var recursive = require('recursive-readdir');
var stripAnsi = require('strip-ansi');
var gzipSize = require('gzip-size').sync;
function canReadAsset(asset) {
return (
/\.(js|css)$/.test(asset) &&
!/service-worker\.js/.test(asset) &&
!/precache-manifest\.[0-9a-f]+\.js/.test(asset)
);
}
// Prints a detailed summary of build files.
function printFileSizesAfterBuild(
webpackStats,
previousSizeMap,
buildFolder,
maxBundleGzipSize,
maxChunkGzipSize
) {
var root = previousSizeMap.root;
var sizes = previousSizeMap.sizes;
var assets = (webpackStats.stats || [webpackStats])
.map(stats =>
stats
.toJson({ all: false, assets: true })
.assets.filter(asset => canReadAsset(asset.name))
.map(asset => {
var fileContents = fs.readFileSync(path.join(root, asset.name));
var size = gzipSize(fileContents);
var previousSize = sizes[removeFileNameHash(root, asset.name)];
var difference = getDifferenceLabel(size, previousSize);
return {
folder: path.join(
path.basename(buildFolder),
path.dirname(asset.name)
),
name: path.basename(asset.name),
size: size,
sizeLabel:
filesize(size) + (difference ? ' (' + difference + ')' : ''),
};
})
)
.reduce((single, all) => all.concat(single), []);
assets.sort((a, b) => b.size - a.size);
var longestSizeLabelLength = Math.max.apply(
null,
assets.map(a => stripAnsi(a.sizeLabel).length)
);
var suggestBundleSplitting = false;
assets.forEach(asset => {
var sizeLabel = asset.sizeLabel;
var sizeLength = stripAnsi(sizeLabel).length;
if (sizeLength < longestSizeLabelLength) {
var rightPadding = ' '.repeat(longestSizeLabelLength - sizeLength);
sizeLabel += rightPadding;
}
var isMainBundle = asset.name.indexOf('main.') === 0;
var maxRecommendedSize = isMainBundle
? maxBundleGzipSize
: maxChunkGzipSize;
var isLarge = maxRecommendedSize && asset.size > maxRecommendedSize;
if (isLarge && path.extname(asset.name) === '.js') {
suggestBundleSplitting = true;
}
console.log(
' ' +
(isLarge ? chalk.yellow(sizeLabel) : sizeLabel) +
' ' +
chalk.dim(asset.folder + path.sep) +
chalk.cyan(asset.name)
);
});
if (suggestBundleSplitting) {
console.log();
console.log(
chalk.yellow('The bundle size is significantly larger than recommended.')
);
console.log(
chalk.yellow(
'Consider reducing it with code splitting: https://create-react-app.dev/docs/code-splitting/'
)
);
console.log(
chalk.yellow(
'You can also analyze the project dependencies: https://goo.gl/LeUzfb'
)
);
}
}
function removeFileNameHash(buildFolder, fileName) {
return fileName
.replace(buildFolder, '')
.replace(/\\/g, '/')
.replace(
/\/?(.*)(\.[0-9a-f]+)(\.chunk)?(\.js|\.css)/,
(match, p1, p2, p3, p4) => p1 + p4
);
}
// Input: 1024, 2048
// Output: "(+1 KB)"
function getDifferenceLabel(currentSize, previousSize) {
var FIFTY_KILOBYTES = 1024 * 50;
var difference = currentSize - previousSize;
var fileSize = !Number.isNaN(difference) ? filesize(difference) : 0;
if (difference >= FIFTY_KILOBYTES) {
return chalk.red('+' + fileSize);
} else if (difference < FIFTY_KILOBYTES && difference > 0) {
return chalk.yellow('+' + fileSize);
} else if (difference < 0) {
return chalk.green(fileSize);
} else {
return '';
}
}
function measureFileSizesBeforeBuild(buildFolder) {
return new Promise(resolve => {
recursive(buildFolder, (err, fileNames) => {
var sizes;
if (!err && fileNames) {
sizes = fileNames.filter(canReadAsset).reduce((memo, fileName) => {
var contents = fs.readFileSync(fileName);
var key = removeFileNameHash(buildFolder, fileName);
memo[key] = gzipSize(contents);
return memo;
}, {});
}
resolve({
root: buildFolder,
sizes: sizes || {},
});
});
});
}
module.exports = {
measureFileSizesBeforeBuild: measureFileSizesBeforeBuild,
printFileSizesAfterBuild: printFileSizesAfterBuild,
};
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-dev-utils/errorOverlayMiddleware.js | packages/react-dev-utils/errorOverlayMiddleware.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
const launchEditor = require('./launchEditor');
const launchEditorEndpoint = require('./launchEditorEndpoint');
module.exports = function createLaunchEditorMiddleware() {
return function launchEditorMiddleware(req, res, next) {
if (req.url.startsWith(launchEditorEndpoint)) {
const lineNumber = parseInt(req.query.lineNumber, 10) || 1;
const colNumber = parseInt(req.query.colNumber, 10) || 1;
launchEditor(req.query.fileName, lineNumber, colNumber);
res.end();
} else {
next();
}
};
};
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-dev-utils/ignoredFiles.js | packages/react-dev-utils/ignoredFiles.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
const path = require('path');
const escape = require('escape-string-regexp');
module.exports = function ignoredFiles(appSrc) {
return new RegExp(
`^(?!${escape(
path.normalize(appSrc + '/').replace(/[\\]+/g, '/')
)}).+/node_modules/`,
'g'
);
};
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-dev-utils/noopServiceWorkerMiddleware.js | packages/react-dev-utils/noopServiceWorkerMiddleware.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
const path = require('path');
module.exports = function createNoopServiceWorkerMiddleware(servedPath) {
return function noopServiceWorkerMiddleware(req, res, next) {
if (req.url === path.posix.join(servedPath, 'service-worker.js')) {
res.setHeader('Content-Type', 'text/javascript');
res.send(
`// This service worker file is effectively a 'no-op' that will reset any
// previous service worker registered for the same host:port combination.
// In the production build, this file is replaced with an actual service worker
// file that will precache your site's local assets.
// See https://github.com/facebook/create-react-app/issues/2272#issuecomment-302832432
self.addEventListener('install', () => self.skipWaiting());
self.addEventListener('activate', () => {
self.clients.matchAll({ type: 'window' }).then(windowClients => {
for (let windowClient of windowClients) {
// Force open pages to refresh, so that they have a chance to load the
// fresh navigation response from the local dev server.
windowClient.navigate(windowClient.url);
}
});
});
`
);
} else {
next();
}
};
};
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-dev-utils/browsersHelper.js | packages/react-dev-utils/browsersHelper.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
const browserslist = require('browserslist');
const chalk = require('chalk');
const os = require('os');
const prompts = require('prompts');
const pkgUp = require('pkg-up');
const fs = require('fs');
const defaultBrowsers = {
production: ['>0.2%', 'not dead', 'not op_mini all'],
development: [
'last 1 chrome version',
'last 1 firefox version',
'last 1 safari version',
],
};
function shouldSetBrowsers(isInteractive) {
if (!isInteractive) {
return Promise.resolve(true);
}
const question = {
type: 'confirm',
name: 'shouldSetBrowsers',
message:
chalk.yellow("We're unable to detect target browsers.") +
`\n\nWould you like to add the defaults to your ${chalk.bold(
'package.json'
)}?`,
initial: true,
};
return prompts(question).then(answer => answer.shouldSetBrowsers);
}
function checkBrowsers(dir, isInteractive, retry = true) {
const current = browserslist.loadConfig({ path: dir });
if (current != null) {
return Promise.resolve(current);
}
if (!retry) {
return Promise.reject(
new Error(
chalk.red(
'As of react-scripts >=2 you must specify targeted browsers.'
) +
os.EOL +
`Please add a ${chalk.underline(
'browserslist'
)} key to your ${chalk.bold('package.json')}.`
)
);
}
return shouldSetBrowsers(isInteractive).then(shouldSetBrowsers => {
if (!shouldSetBrowsers) {
return checkBrowsers(dir, isInteractive, false);
}
return (
pkgUp({ cwd: dir })
.then(filePath => {
if (filePath == null) {
return Promise.reject();
}
const pkg = JSON.parse(fs.readFileSync(filePath));
pkg['browserslist'] = defaultBrowsers;
fs.writeFileSync(filePath, JSON.stringify(pkg, null, 2) + os.EOL);
browserslist.clearCaches();
console.log();
console.log(
`${chalk.green('Set target browsers:')} ${chalk.cyan(
defaultBrowsers.join(', ')
)}`
);
console.log();
})
// Swallow any error
.catch(() => {})
.then(() => checkBrowsers(dir, isInteractive, false))
);
});
}
module.exports = { defaultBrowsers, checkBrowsers };
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-dev-utils/evalSourceMapMiddleware.js | packages/react-dev-utils/evalSourceMapMiddleware.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
function base64SourceMap(source) {
const base64 = Buffer.from(JSON.stringify(source.map()), 'utf8').toString(
'base64'
);
return `data:application/json;charset=utf-8;base64,${base64}`;
}
function getSourceById(server, id) {
const module = Array.from(server._stats.compilation.modules).find(
m => server._stats.compilation.chunkGraph.getModuleId(m) == id
);
return module.originalSource();
}
/*
* Middleware responsible for retrieving a generated source
* Receives a webpack internal url: "webpack-internal:///<module-id>"
* Returns a generated source: "<source-text><sourceMappingURL><sourceURL>"
*
* Based on EvalSourceMapDevToolModuleTemplatePlugin.js
*/
module.exports = function createEvalSourceMapMiddleware(server) {
return function handleWebpackInternalMiddleware(req, res, next) {
if (req.url.startsWith('/__get-internal-source')) {
const fileName = req.query.fileName;
const id = fileName.match(/webpack-internal:\/\/\/(.+)/)[1];
if (!id || !server._stats) {
next();
}
const source = getSourceById(server, id);
const sourceMapURL = `//# sourceMappingURL=${base64SourceMap(source)}`;
const sourceURL = `//# sourceURL=webpack-internal:///${module.id}`;
res.end(`${source.source()}\n${sourceMapURL}\n${sourceURL}`);
} else {
next();
}
};
};
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-dev-utils/printBuildError.js | packages/react-dev-utils/printBuildError.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
const chalk = require('chalk');
module.exports = function printBuildError(err) {
const message = err != null && err.message;
const stack = err != null && err.stack;
// Add more helpful message for Terser error
if (
stack &&
typeof message === 'string' &&
message.indexOf('from Terser') !== -1
) {
try {
const matched = /(.+)\[(.+):(.+),(.+)\]\[.+\]/.exec(stack);
if (!matched) {
throw new Error('Using errors for control flow is bad.');
}
const problemPath = matched[2];
const line = matched[3];
const column = matched[4];
console.log(
'Failed to minify the code from this file: \n\n',
chalk.yellow(
`\t${problemPath}:${line}${column !== '0' ? ':' + column : ''}`
),
'\n'
);
} catch (ignored) {
console.log('Failed to minify the bundle.', err);
}
console.log('Read more here: https://cra.link/failed-to-minify');
} else {
console.log((message || err) + '\n');
}
console.log();
};
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-dev-utils/InlineChunkHtmlPlugin.js | packages/react-dev-utils/InlineChunkHtmlPlugin.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
class InlineChunkHtmlPlugin {
constructor(htmlWebpackPlugin, tests) {
this.htmlWebpackPlugin = htmlWebpackPlugin;
this.tests = tests;
}
getInlinedTag(publicPath, assets, tag) {
if (tag.tagName !== 'script' || !(tag.attributes && tag.attributes.src)) {
return tag;
}
const scriptName = publicPath
? tag.attributes.src.replace(publicPath, '')
: tag.attributes.src;
if (!this.tests.some(test => scriptName.match(test))) {
return tag;
}
const asset = assets[scriptName];
if (asset == null) {
return tag;
}
return { tagName: 'script', innerHTML: asset.source(), closeTag: true };
}
apply(compiler) {
let publicPath = compiler.options.output.publicPath || '';
if (publicPath && !publicPath.endsWith('/')) {
publicPath += '/';
}
compiler.hooks.compilation.tap('InlineChunkHtmlPlugin', compilation => {
const tagFunction = tag =>
this.getInlinedTag(publicPath, compilation.assets, tag);
const hooks = this.htmlWebpackPlugin.getHooks(compilation);
hooks.alterAssetTagGroups.tap('InlineChunkHtmlPlugin', assets => {
assets.headTags = assets.headTags.map(tagFunction);
assets.bodyTags = assets.bodyTags.map(tagFunction);
});
// Still emit the runtime chunk for users who do not use our generated
// index.html file.
// hooks.afterEmit.tap('InlineChunkHtmlPlugin', () => {
// Object.keys(compilation.assets).forEach(assetName => {
// if (this.tests.some(test => assetName.match(test))) {
// delete compilation.assets[assetName];
// }
// });
// });
});
}
}
module.exports = InlineChunkHtmlPlugin;
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-dev-utils/ModuleNotFoundPlugin.js | packages/react-dev-utils/ModuleNotFoundPlugin.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
const chalk = require('chalk');
const findUp = require('find-up');
const path = require('path');
class ModuleNotFoundPlugin {
constructor(appPath, yarnLockFile) {
this.appPath = appPath;
this.yarnLockFile = yarnLockFile;
this.useYarnCommand = this.useYarnCommand.bind(this);
this.getRelativePath = this.getRelativePath.bind(this);
this.prettierError = this.prettierError.bind(this);
}
useYarnCommand() {
try {
return findUp.sync('yarn.lock', { cwd: this.appPath }) != null;
} catch (_) {
return false;
}
}
getRelativePath(_file) {
let file = path.relative(this.appPath, _file);
if (file.startsWith('..')) {
file = _file;
} else if (!file.startsWith('.')) {
file = '.' + path.sep + file;
}
return file;
}
prettierError(err) {
let { details: _details = '', origin } = err;
if (origin == null) {
const caseSensitivity =
err.message &&
/\[CaseSensitivePathsPlugin\] `(.*?)` .* `(.*?)`/.exec(err.message);
if (caseSensitivity) {
const [, incorrectPath, actualName] = caseSensitivity;
const actualFile = this.getRelativePath(
path.join(path.dirname(incorrectPath), actualName)
);
const incorrectName = path.basename(incorrectPath);
err.message = `Cannot find file: '${incorrectName}' does not match the corresponding name on disk: '${actualFile}'.`;
}
return err;
}
const file = this.getRelativePath(origin.resource);
let details = _details.split('\n');
const request = /resolve '(.*?)' in '(.*?)'/.exec(details);
if (request) {
const isModule = details[1] && details[1].includes('module');
const isFile = details[1] && details[1].includes('file');
let [, target, context] = request;
context = this.getRelativePath(context);
if (isModule) {
const isYarn = this.useYarnCommand();
details = [
`Cannot find module: '${target}'. Make sure this package is installed.`,
'',
'You can install this package by running: ' +
(isYarn
? chalk.bold(`yarn add ${target}`)
: chalk.bold(`npm install ${target}`)) +
'.',
];
} else if (isFile) {
details = [`Cannot find file '${target}' in '${context}'.`];
} else {
details = [err.message];
}
} else {
details = [err.message];
}
err.message = [file, ...details].join('\n').replace('Error: ', '');
const isModuleScopePluginError =
err.error && err.error.__module_scope_plugin;
if (isModuleScopePluginError) {
err.message = err.message.replace('Module not found: ', '');
}
return err;
}
apply(compiler) {
const { prettierError } = this;
compiler.hooks.make.intercept({
register(tap) {
if (!(tap.name === 'MultiEntryPlugin' || tap.name === 'EntryPlugin')) {
return tap;
}
return Object.assign({}, tap, {
fn: (compilation, callback) => {
tap.fn(compilation, (err, ...args) => {
if (err && err.name === 'ModuleNotFoundError') {
err = prettierError(err);
}
callback(err, ...args);
});
},
});
},
});
compiler.hooks.normalModuleFactory.tap('ModuleNotFoundPlugin', nmf => {
nmf.hooks.afterResolve.intercept({
register(tap) {
if (tap.name !== 'CaseSensitivePathsPlugin') {
return tap;
}
return Object.assign({}, tap, {
fn: (compilation, callback) => {
tap.fn(compilation, (err, ...args) => {
if (
err &&
err.message &&
err.message.includes('CaseSensitivePathsPlugin')
) {
err = prettierError(err);
}
callback(err, ...args);
});
},
});
},
});
});
}
}
module.exports = ModuleNotFoundPlugin;
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-dev-utils/refreshOverlayInterop.js | packages/react-dev-utils/refreshOverlayInterop.js | // @remove-on-eject-begin
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
// @remove-on-eject-end
'use strict';
const {
dismissRuntimeErrors,
reportRuntimeError,
} = require('react-error-overlay');
module.exports = {
clearRuntimeErrors: dismissRuntimeErrors,
handleRuntimeError: reportRuntimeError,
};
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-dev-utils/immer.js | packages/react-dev-utils/immer.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
var immer = require('immer');
module.exports = immer;
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-dev-utils/ForkTsCheckerWebpackPlugin.js | packages/react-dev-utils/ForkTsCheckerWebpackPlugin.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
var ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
module.exports = ForkTsCheckerWebpackPlugin;
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-dev-utils/__tests__/getPublicUrlOrPath.test.js | packages/react-dev-utils/__tests__/getPublicUrlOrPath.test.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
const getPublicUrlOrPath = require('../getPublicUrlOrPath');
const tests = [
// DEVELOPMENT with homepage
{ dev: true, homepage: '/', expect: '/' },
{ dev: true, homepage: '/test', expect: '/test/' },
{ dev: true, homepage: '/test/', expect: '/test/' },
{ dev: true, homepage: './', expect: '/' },
{ dev: true, homepage: '../', expect: '/' },
{ dev: true, homepage: '../test', expect: '/' },
{ dev: true, homepage: './test/path', expect: '/' },
{ dev: true, homepage: 'https://create-react-app.dev/', expect: '/' },
{
dev: true,
homepage: 'https://create-react-app.dev/test',
expect: '/test/',
},
// DEVELOPMENT with publicURL
{ dev: true, publicUrl: '/', expect: '/' },
{ dev: true, publicUrl: '/test', expect: '/test/' },
{ dev: true, publicUrl: '/test/', expect: '/test/' },
{ dev: true, publicUrl: './', expect: '/' },
{ dev: true, publicUrl: '../', expect: '/' },
{ dev: true, publicUrl: '../test', expect: '/' },
{ dev: true, publicUrl: './test/path', expect: '/' },
{ dev: true, publicUrl: 'https://create-react-app.dev/', expect: '/' },
{
dev: true,
publicUrl: 'https://create-react-app.dev/test',
expect: '/test/',
},
// DEVELOPMENT with publicURL and homepage
{ dev: true, publicUrl: '/', homepage: '/test', expect: '/' },
{ dev: true, publicUrl: '/test', homepage: '/path', expect: '/test/' },
{ dev: true, publicUrl: '/test/', homepage: '/test/path', expect: '/test/' },
{ dev: true, publicUrl: './', homepage: '/test', expect: '/' },
{ dev: true, publicUrl: '../', homepage: '/test', expect: '/' },
{ dev: true, publicUrl: '../test', homepage: '/test', expect: '/' },
{ dev: true, publicUrl: './test/path', homepage: '/test', expect: '/' },
{
dev: true,
publicUrl: 'https://create-react-app.dev/',
homepage: '/test',
expect: '/',
},
{
dev: true,
publicUrl: 'https://create-react-app.dev/test',
homepage: '/path',
expect: '/test/',
},
// PRODUCTION with homepage
{ dev: false, homepage: '/', expect: '/' },
{ dev: false, homepage: '/test', expect: '/test/' },
{ dev: false, homepage: '/test/', expect: '/test/' },
{ dev: false, homepage: './', expect: './' },
{ dev: false, homepage: '../', expect: '../' },
{ dev: false, homepage: '../test', expect: '../test/' },
{ dev: false, homepage: './test/path', expect: './test/path/' },
{ dev: false, homepage: 'https://create-react-app.dev/', expect: '/' },
{
dev: false,
homepage: 'https://create-react-app.dev/test',
expect: '/test/',
},
// PRODUCTION with publicUrl
{ dev: false, publicUrl: '/', expect: '/' },
{ dev: false, publicUrl: '/test', expect: '/test/' },
{ dev: false, publicUrl: '/test/', expect: '/test/' },
{ dev: false, publicUrl: './', expect: './' },
{ dev: false, publicUrl: '../', expect: '../' },
{ dev: false, publicUrl: '../test', expect: '../test/' },
{ dev: false, publicUrl: './test/path', expect: './test/path/' },
{
dev: false,
publicUrl: 'https://create-react-app.dev/',
expect: 'https://create-react-app.dev/',
},
{
dev: false,
publicUrl: 'https://create-react-app.dev/test',
expect: 'https://create-react-app.dev/test/',
},
// PRODUCTION with publicUrl and homepage
{ dev: false, publicUrl: '/', homepage: '/test', expect: '/' },
{ dev: false, publicUrl: '/test', homepage: '/path', expect: '/test/' },
{ dev: false, publicUrl: '/test/', homepage: '/test/path', expect: '/test/' },
{ dev: false, publicUrl: './', homepage: '/test', expect: './' },
{ dev: false, publicUrl: '../', homepage: '/test', expect: '../' },
{ dev: false, publicUrl: '../test', homepage: '/test', expect: '../test/' },
{
dev: false,
publicUrl: './test/path',
homepage: '/test',
expect: './test/path/',
},
{
dev: false,
publicUrl: 'https://create-react-app.dev/',
homepage: '/test',
expect: 'https://create-react-app.dev/',
},
{
dev: false,
publicUrl: 'https://create-react-app.dev/test',
homepage: '/path',
expect: 'https://create-react-app.dev/test/',
},
];
describe('getPublicUrlOrPath', () => {
tests.forEach(t =>
it(JSON.stringify(t), () => {
const actual = getPublicUrlOrPath(t.dev, t.homepage, t.publicUrl);
expect(actual).toBe(t.expect);
})
);
});
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-dev-utils/__tests__/ignoredFiles.test.js | packages/react-dev-utils/__tests__/ignoredFiles.test.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
const ignoredFiles = require('../ignoredFiles');
describe('ignore watch files regex', () => {
it('normal file', () => {
const appSrc = '/root/src/';
const isIgnored = ignoredFiles(appSrc).test('/foo');
const isIgnoredInSrc = ignoredFiles(appSrc).test('/root/src/foo');
expect(isIgnored).toBe(false);
expect(isIgnoredInSrc).toBe(false);
});
it('node modules', () => {
const appSrc = '/root/src/';
const isIgnored = ignoredFiles(appSrc).test('/root/node_modules/foo');
expect(isIgnored).toBe(true);
});
it('node modules inside source directory', () => {
const appSrc = '/root/src/';
const isIgnored = ignoredFiles(appSrc).test('/root/src/node_modules/foo');
const isIgnoredMoreThanOneLevel = ignoredFiles(appSrc).test(
'/root/src/bar/node_modules/foo'
);
expect(isIgnored).toBe(false);
expect(isIgnoredMoreThanOneLevel).toBe(false);
});
it('path contains source directory', () => {
const appSrc = '/root/src/';
const isIgnored = ignoredFiles(appSrc).test(
'/bar/root/src/node_modules/foo'
);
expect(isIgnored).toBe(true);
});
it('path starts with source directory', () => {
const appSrc = '/root/src/';
const isIgnored = ignoredFiles(appSrc).test('/root/src2/node_modules/foo');
expect(isIgnored).toBe(true);
});
});
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-dev-utils/__tests__/getCSSModuleLocalIdent.test.js | packages/react-dev-utils/__tests__/getCSSModuleLocalIdent.test.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
const getCSSModuleLocalIdent = require('../getCSSModuleLocalIdent');
const rootContext = '/path';
const defaultClassName = 'class';
const options = { context: undefined, hashPrefix: '', regExp: null };
const tests = [
{
resourcePath: '/path/to/file.module.css',
expected: 'file_class__jqNYY',
},
{
resourcePath: '/path/to/file.module.scss',
expected: 'file_class__BjEjJ',
},
{
resourcePath: '/path/to/file.module.sass',
expected: 'file_class__dINZX',
},
{
resourcePath: '/path/to/file.name.module.css',
expected: 'file_name_class__XpUJW',
},
];
describe('getCSSModuleLocalIdent', () => {
tests.forEach(test => {
const { className = defaultClassName, expected, resourcePath } = test;
it(JSON.stringify({ resourcePath, className }), () => {
const ident = getCSSModuleLocalIdent(
{
resourcePath,
rootContext,
},
'[hash:base64]',
className,
options
);
expect(ident).toBe(expected);
});
});
});
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/babel-preset-react-app/index.js | packages/babel-preset-react-app/index.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
const create = require('./create');
module.exports = function (api, opts) {
// This is similar to how `env` works in Babel:
// https://babeljs.io/docs/usage/babelrc/#env-option
// We are not using `env` because it’s ignored in versions > babel-core@6.10.4:
// https://github.com/babel/babel/issues/4539
// https://github.com/facebook/create-react-app/issues/720
// It’s also nice that we can enforce `NODE_ENV` being specified.
const env = process.env.BABEL_ENV || process.env.NODE_ENV;
return create(api, opts, env);
};
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/babel-preset-react-app/test.js | packages/babel-preset-react-app/test.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
const create = require('./create');
module.exports = function (api, opts) {
return create(api, Object.assign({ helpers: false }, opts), 'test');
};
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/babel-preset-react-app/dependencies.js | packages/babel-preset-react-app/dependencies.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
const path = require('path');
const validateBoolOption = (name, value, defaultValue) => {
if (typeof value === 'undefined') {
value = defaultValue;
}
if (typeof value !== 'boolean') {
throw new Error(`Preset react-app: '${name}' option must be a boolean.`);
}
return value;
};
module.exports = function (api, opts) {
if (!opts) {
opts = {};
}
// This is similar to how `env` works in Babel:
// https://babeljs.io/docs/usage/babelrc/#env-option
// We are not using `env` because it’s ignored in versions > babel-core@6.10.4:
// https://github.com/babel/babel/issues/4539
// https://github.com/facebook/create-react-app/issues/720
// It’s also nice that we can enforce `NODE_ENV` being specified.
var env = process.env.BABEL_ENV || process.env.NODE_ENV;
var isEnvDevelopment = env === 'development';
var isEnvProduction = env === 'production';
var isEnvTest = env === 'test';
var areHelpersEnabled = validateBoolOption('helpers', opts.helpers, false);
var useAbsoluteRuntime = validateBoolOption(
'absoluteRuntime',
opts.absoluteRuntime,
true
);
var absoluteRuntimePath = undefined;
if (useAbsoluteRuntime) {
absoluteRuntimePath = path.dirname(
require.resolve('@babel/runtime/package.json')
);
}
if (!isEnvDevelopment && !isEnvProduction && !isEnvTest) {
throw new Error(
'Using `babel-preset-react-app` requires that you specify `NODE_ENV` or ' +
'`BABEL_ENV` environment variables. Valid values are "development", ' +
'"test", and "production". Instead, received: ' +
JSON.stringify(env) +
'.'
);
}
return {
// Babel assumes ES Modules, which isn't safe until CommonJS
// dies. This changes the behavior to assume CommonJS unless
// an `import` or `export` is present in the file.
// https://github.com/webpack/webpack/issues/4039#issuecomment-419284940
sourceType: 'unambiguous',
presets: [
isEnvTest && [
// ES features necessary for user's Node version
require('@babel/preset-env').default,
{
targets: {
node: 'current',
},
// Exclude transforms that make all code slower
exclude: ['transform-typeof-symbol'],
},
],
(isEnvProduction || isEnvDevelopment) && [
// Latest stable ECMAScript features
require('@babel/preset-env').default,
{
// Allow importing core-js in entrypoint and use browserlist to select polyfills
useBuiltIns: 'entry',
// Set the corejs version we are using to avoid warnings in console
// This will need to change once we upgrade to corejs@3
corejs: 3,
// Exclude transforms that make all code slower
exclude: ['transform-typeof-symbol'],
},
],
].filter(Boolean),
plugins: [
// Disabled as it's handled automatically by preset-env, and `selectiveLoose` isn't
// yet merged into babel: https://github.com/babel/babel/pull/9486
// Related: https://github.com/facebook/create-react-app/pull/8215
// [
// require('@babel/plugin-transform-destructuring').default,
// {
// // Use loose mode for performance:
// // https://github.com/facebook/create-react-app/issues/5602
// loose: false,
// selectiveLoose: [
// 'useState',
// 'useEffect',
// 'useContext',
// 'useReducer',
// 'useCallback',
// 'useMemo',
// 'useRef',
// 'useImperativeHandle',
// 'useLayoutEffect',
// 'useDebugValue',
// ],
// },
// ],
// Polyfills the runtime needed for async/await, generators, and friends
// https://babeljs.io/docs/en/babel-plugin-transform-runtime
[
require('@babel/plugin-transform-runtime').default,
{
corejs: false,
helpers: areHelpersEnabled,
// By default, babel assumes babel/runtime version 7.0.0-beta.0,
// explicitly resolving to match the provided helper functions.
// https://github.com/babel/babel/issues/10261
version: require('@babel/runtime/package.json').version,
regenerator: true,
// https://babeljs.io/docs/en/babel-plugin-transform-runtime#useesmodules
// We should turn this on once the lowest version of Node LTS
// supports ES Modules.
useESModules: isEnvDevelopment || isEnvProduction,
// Undocumented option that lets us encapsulate our runtime, ensuring
// the correct version is used
// https://github.com/babel/babel/blob/090c364a90fe73d36a30707fc612ce037bdbbb24/packages/babel-plugin-transform-runtime/src/index.js#L35-L42
absoluteRuntime: absoluteRuntimePath,
},
],
].filter(Boolean),
};
};
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/babel-preset-react-app/create.js | packages/babel-preset-react-app/create.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
const path = require('path');
const validateBoolOption = (name, value, defaultValue) => {
if (typeof value === 'undefined') {
value = defaultValue;
}
if (typeof value !== 'boolean') {
throw new Error(`Preset react-app: '${name}' option must be a boolean.`);
}
return value;
};
module.exports = function (api, opts, env) {
if (!opts) {
opts = {};
}
var isEnvDevelopment = env === 'development';
var isEnvProduction = env === 'production';
var isEnvTest = env === 'test';
var useESModules = validateBoolOption(
'useESModules',
opts.useESModules,
isEnvDevelopment || isEnvProduction
);
var isFlowEnabled = validateBoolOption('flow', opts.flow, true);
var isTypeScriptEnabled = validateBoolOption(
'typescript',
opts.typescript,
true
);
var areHelpersEnabled = validateBoolOption('helpers', opts.helpers, true);
var useAbsoluteRuntime = validateBoolOption(
'absoluteRuntime',
opts.absoluteRuntime,
true
);
var absoluteRuntimePath = undefined;
if (useAbsoluteRuntime) {
absoluteRuntimePath = path.dirname(
require.resolve('@babel/runtime/package.json')
);
}
if (!isEnvDevelopment && !isEnvProduction && !isEnvTest) {
throw new Error(
'Using `babel-preset-react-app` requires that you specify `NODE_ENV` or ' +
'`BABEL_ENV` environment variables. Valid values are "development", ' +
'"test", and "production". Instead, received: ' +
JSON.stringify(env) +
'.'
);
}
return {
presets: [
isEnvTest && [
// ES features necessary for user's Node version
require('@babel/preset-env').default,
{
targets: {
node: 'current',
},
},
],
(isEnvProduction || isEnvDevelopment) && [
// Latest stable ECMAScript features
require('@babel/preset-env').default,
{
// Allow importing core-js in entrypoint and use browserlist to select polyfills
useBuiltIns: 'entry',
// Set the corejs version we are using to avoid warnings in console
corejs: 3,
// Exclude transforms that make all code slower
exclude: ['transform-typeof-symbol'],
},
],
[
require('@babel/preset-react').default,
{
// Adds component stack to warning messages
// Adds __self attribute to JSX which React will use for some warnings
development: isEnvDevelopment || isEnvTest,
// Will use the native built-in instead of trying to polyfill
// behavior for any plugins that require one.
...(opts.runtime !== 'automatic' ? { useBuiltIns: true } : {}),
runtime: opts.runtime || 'classic',
},
],
isTypeScriptEnabled && [require('@babel/preset-typescript').default],
].filter(Boolean),
plugins: [
// Strip flow types before any other transform, emulating the behavior
// order as-if the browser supported all of the succeeding features
// https://github.com/facebook/create-react-app/pull/5182
// We will conditionally enable this plugin below in overrides as it clashes with
// @babel/plugin-proposal-decorators when using TypeScript.
// https://github.com/facebook/create-react-app/issues/5741
isFlowEnabled && [
require('@babel/plugin-transform-flow-strip-types').default,
false,
],
// Experimental macros support. Will be documented after it's had some time
// in the wild.
require('babel-plugin-macros'),
// Disabled as it's handled automatically by preset-env, and `selectiveLoose` isn't
// yet merged into babel: https://github.com/babel/babel/pull/9486
// Related: https://github.com/facebook/create-react-app/pull/8215
// [
// require('@babel/plugin-transform-destructuring').default,
// {
// // Use loose mode for performance:
// // https://github.com/facebook/create-react-app/issues/5602
// loose: false,
// selectiveLoose: [
// 'useState',
// 'useEffect',
// 'useContext',
// 'useReducer',
// 'useCallback',
// 'useMemo',
// 'useRef',
// 'useImperativeHandle',
// 'useLayoutEffect',
// 'useDebugValue',
// ],
// },
// ],
// Turn on legacy decorators for TypeScript files
isTypeScriptEnabled && [
require('@babel/plugin-proposal-decorators').default,
false,
],
// class { handleClick = () => { } }
// Enable loose mode to use assignment instead of defineProperty
// See discussion in https://github.com/facebook/create-react-app/issues/4263
// Note:
// 'loose' mode configuration must be the same for
// * @babel/plugin-proposal-class-properties
// * @babel/plugin-proposal-private-methods
// * @babel/plugin-proposal-private-property-in-object
// (when they are enabled)
[
require('@babel/plugin-proposal-class-properties').default,
{
loose: true,
},
],
[
require('@babel/plugin-proposal-private-methods').default,
{
loose: true,
},
],
[
require('@babel/plugin-proposal-private-property-in-object').default,
{
loose: true,
},
],
// Adds Numeric Separators
require('@babel/plugin-proposal-numeric-separator').default,
// Polyfills the runtime needed for async/await, generators, and friends
// https://babeljs.io/docs/en/babel-plugin-transform-runtime
[
require('@babel/plugin-transform-runtime').default,
{
corejs: false,
helpers: areHelpersEnabled,
// By default, babel assumes babel/runtime version 7.0.0-beta.0,
// explicitly resolving to match the provided helper functions.
// https://github.com/babel/babel/issues/10261
version: require('@babel/runtime/package.json').version,
regenerator: true,
// https://babeljs.io/docs/en/babel-plugin-transform-runtime#useesmodules
// We should turn this on once the lowest version of Node LTS
// supports ES Modules.
useESModules,
// Undocumented option that lets us encapsulate our runtime, ensuring
// the correct version is used
// https://github.com/babel/babel/blob/090c364a90fe73d36a30707fc612ce037bdbbb24/packages/babel-plugin-transform-runtime/src/index.js#L35-L42
absoluteRuntime: absoluteRuntimePath,
},
],
isEnvProduction && [
// Remove PropTypes from production build
require('babel-plugin-transform-react-remove-prop-types').default,
{
removeImport: true,
},
],
// Optional chaining and nullish coalescing are supported in @babel/preset-env,
// but not yet supported in webpack due to support missing from acorn.
// These can be removed once webpack has support.
// See https://github.com/facebook/create-react-app/issues/8445#issuecomment-588512250
require('@babel/plugin-proposal-optional-chaining').default,
require('@babel/plugin-proposal-nullish-coalescing-operator').default,
].filter(Boolean),
overrides: [
isFlowEnabled && {
exclude: /\.tsx?$/,
plugins: [require('@babel/plugin-transform-flow-strip-types').default],
},
isTypeScriptEnabled && {
test: /\.tsx?$/,
plugins: [
[
require('@babel/plugin-proposal-decorators').default,
{ legacy: true },
],
],
},
].filter(Boolean),
};
};
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/babel-preset-react-app/prod.js | packages/babel-preset-react-app/prod.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
const create = require('./create');
module.exports = function (api, opts) {
return create(api, Object.assign({ helpers: false }, opts), 'production');
};
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/babel-preset-react-app/dev.js | packages/babel-preset-react-app/dev.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
const create = require('./create');
module.exports = function (api, opts) {
return create(api, Object.assign({ helpers: false }, opts), 'development');
};
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/babel-preset-react-app/webpack-overrides.js | packages/babel-preset-react-app/webpack-overrides.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
const crypto = require('crypto');
const macroCheck = new RegExp('[./]macro');
module.exports = function () {
return {
// This function transforms the Babel configuration on a per-file basis
config(config, { source }) {
// Babel Macros are notoriously hard to cache, so they shouldn't be
// https://github.com/babel/babel/issues/8497
// We naively detect macros using their package suffix and add a random token
// to the caller, a valid option accepted by Babel, to compose a one-time
// cacheIdentifier for the file. We cannot tune the loader options on a per
// file basis.
if (macroCheck.test(source)) {
return Object.assign({}, config.options, {
caller: Object.assign({}, config.options.caller, {
craInvalidationToken: crypto.randomBytes(32).toString('hex'),
}),
});
}
return config.options;
},
};
};
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-app-polyfill/ie9.js | packages/react-app-polyfill/ie9.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
require('./ie11');
// React 16+ relies on Map, Set, and requestAnimationFrame
require('core-js/features/map');
require('core-js/features/set');
require('raf').polyfill();
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-app-polyfill/ie11.js | packages/react-app-polyfill/ie11.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
if (typeof Promise === 'undefined') {
// Rejection tracking prevents a common issue where React gets into an
// inconsistent state due to an error, but it gets swallowed by a Promise,
// and the user has no idea what causes React's erratic future behavior.
require('promise/lib/rejection-tracking').enable();
self.Promise = require('promise/lib/es6-extensions.js');
}
// Make sure we're in a Browser-like environment before importing polyfills
// This prevents `fetch()` from being imported in a Node test environment
if (typeof window !== 'undefined') {
// fetch() polyfill for making API calls.
require('whatwg-fetch');
}
// Object.assign() is commonly used with React.
// It will use the native implementation if it's present and isn't buggy.
Object.assign = require('object-assign');
// Support for...of (a commonly used syntax feature that requires Symbols)
require('core-js/features/symbol');
// Support iterable spread (...Set, ...Map)
require('core-js/features/array/from');
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-app-polyfill/jsdom.js | packages/react-app-polyfill/jsdom.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
// Make sure we're in a Browser-like environment before importing polyfills
// This prevents `fetch()` from being imported in a Node test environment
if (typeof window !== 'undefined') {
// fetch() polyfill for making API calls.
require('whatwg-fetch');
}
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-app-polyfill/stable.js | packages/react-app-polyfill/stable.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
// Polyfill stable language features.
// It's recommended to use @babel/preset-env and browserslist
// to only include the polyfills necessary for the target browsers.
require('core-js/stable');
require('regenerator-runtime/runtime');
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/create-react-app/index.js | packages/create-react-app/index.js | #!/usr/bin/env node
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// /!\ DO NOT MODIFY THIS FILE /!\
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// create-react-app is installed globally on people's computers. This means
// that it is extremely difficult to have them upgrade the version and
// because there's only one global version installed, it is very prone to
// breaking changes.
//
// The only job of create-react-app is to init the repository and then
// forward all the commands to the local version of create-react-app.
//
// If you need to add a new command, please add it to the scripts/ folder.
//
// The only reason to modify this file is to add more warnings and
// troubleshooting information for the `create-react-app` command.
//
// Do not make breaking changes! We absolutely don't want to have to
// tell people to update their global version of create-react-app.
//
// Also be careful with new language features.
// This file must work on Node 0.10+.
//
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// /!\ DO NOT MODIFY THIS FILE /!\
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
'use strict';
const currentNodeVersion = process.versions.node;
const semver = currentNodeVersion.split('.');
const major = semver[0];
if (major < 14) {
console.error(
'You are running Node ' +
currentNodeVersion +
'.\n' +
'Create React App requires Node 14 or higher. \n' +
'Please update your version of Node.'
);
process.exit(1);
}
const { init } = require('./createReactApp');
init();
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/create-react-app/createReactApp.js | packages/create-react-app/createReactApp.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// /!\ DO NOT MODIFY THIS FILE /!\
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// The only job of create-react-app is to init the repository and then
// forward all the commands to the local version of create-react-app.
//
// If you need to add a new command, please add it to the scripts/ folder.
//
// The only reason to modify this file is to add more warnings and
// troubleshooting information for the `create-react-app` command.
//
// Do not make breaking changes! We absolutely don't want to have to
// tell people to update their global version of create-react-app.
//
// Also be careful with new language features.
// This file must work on Node 10+.
//
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// /!\ DO NOT MODIFY THIS FILE /!\
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
'use strict';
const https = require('https');
const chalk = require('chalk');
const commander = require('commander');
const dns = require('dns');
const envinfo = require('envinfo');
const execSync = require('child_process').execSync;
const fs = require('fs-extra');
const hyperquest = require('hyperquest');
const prompts = require('prompts');
const os = require('os');
const path = require('path');
const semver = require('semver');
const spawn = require('cross-spawn');
const tmp = require('tmp');
const unpack = require('tar-pack').unpack;
const url = require('url');
const validateProjectName = require('validate-npm-package-name');
const packageJson = require('./package.json');
function isUsingYarn() {
return (process.env.npm_config_user_agent || '').indexOf('yarn') === 0;
}
function hasGivenWarning() {
const localWarningFilePath = path.join(
__dirname,
'given-deprecation-warning'
);
return fs.existsSync(localWarningFilePath);
}
function writeWarningFile() {
const localWarningFilePath = path.join(
__dirname,
'given-deprecation-warning'
);
fs.writeFileSync(localWarningFilePath, 'true');
}
let projectName;
function init() {
if (!hasGivenWarning()) {
console.log(chalk.yellow.bold('create-react-app is deprecated.'));
console.log('');
console.log(
'You can find a list of up-to-date React frameworks on react.dev'
);
console.log(
'For more info see:' + chalk.underline('https://react.dev/link/cra')
);
console.log('');
console.log(
chalk.grey('This error message will only be shown once per install.')
);
writeWarningFile();
}
const program = new commander.Command(packageJson.name)
.version(packageJson.version)
.arguments('<project-directory>')
.usage(`${chalk.green('<project-directory>')} [options]`)
.action(name => {
projectName = name;
})
.option('--verbose', 'print additional logs')
.option('--info', 'print environment debug info')
.option(
'--scripts-version <alternative-package>',
'use a non-standard version of react-scripts'
)
.option(
'--template <path-to-template>',
'specify a template for the created project'
)
.option('--use-pnp')
.allowUnknownOption()
.on('--help', () => {
console.log(
` Only ${chalk.green('<project-directory>')} is required.`
);
console.log();
console.log(
` A custom ${chalk.cyan('--scripts-version')} can be one of:`
);
console.log(` - a specific npm version: ${chalk.green('0.8.2')}`);
console.log(` - a specific npm tag: ${chalk.green('@next')}`);
console.log(
` - a custom fork published on npm: ${chalk.green(
'my-react-scripts'
)}`
);
console.log(
` - a local path relative to the current working directory: ${chalk.green(
'file:../my-react-scripts'
)}`
);
console.log(
` - a .tgz archive: ${chalk.green(
'https://mysite.com/my-react-scripts-0.8.2.tgz'
)}`
);
console.log(
` - a .tar.gz archive: ${chalk.green(
'https://mysite.com/my-react-scripts-0.8.2.tar.gz'
)}`
);
console.log(
` It is not needed unless you specifically want to use a fork.`
);
console.log();
console.log(` A custom ${chalk.cyan('--template')} can be one of:`);
console.log(
` - a custom template published on npm: ${chalk.green(
'cra-template-typescript'
)}`
);
console.log(
` - a local path relative to the current working directory: ${chalk.green(
'file:../my-custom-template'
)}`
);
console.log(
` - a .tgz archive: ${chalk.green(
'https://mysite.com/my-custom-template-0.8.2.tgz'
)}`
);
console.log(
` - a .tar.gz archive: ${chalk.green(
'https://mysite.com/my-custom-template-0.8.2.tar.gz'
)}`
);
console.log();
console.log(
` If you have any problems, do not hesitate to file an issue:`
);
console.log(
` ${chalk.cyan(
'https://github.com/facebook/create-react-app/issues/new'
)}`
);
console.log();
})
.parse(process.argv);
if (program.info) {
console.log(chalk.bold('\nEnvironment Info:'));
console.log(
`\n current version of ${packageJson.name}: ${packageJson.version}`
);
console.log(` running from ${__dirname}`);
return envinfo
.run(
{
System: ['OS', 'CPU'],
Binaries: ['Node', 'npm', 'Yarn'],
Browsers: [
'Chrome',
'Edge',
'Internet Explorer',
'Firefox',
'Safari',
],
npmPackages: ['react', 'react-dom', 'react-scripts'],
npmGlobalPackages: ['create-react-app'],
},
{
duplicates: true,
showNotFound: true,
}
)
.then(console.log);
}
if (typeof projectName === 'undefined') {
console.error('Please specify the project directory:');
console.log(
` ${chalk.cyan(program.name())} ${chalk.green('<project-directory>')}`
);
console.log();
console.log('For example:');
console.log(
` ${chalk.cyan(program.name())} ${chalk.green('my-react-app')}`
);
console.log();
console.log(
`Run ${chalk.cyan(`${program.name()} --help`)} to see all options.`
);
process.exit(1);
}
// We first check the registry directly via the API, and if that fails, we try
// the slower `npm view [package] version` command.
//
// This is important for users in environments where direct access to npm is
// blocked by a firewall, and packages are provided exclusively via a private
// registry.
checkForLatestVersion()
.catch(() => {
try {
return execSync('npm view create-react-app version').toString().trim();
} catch (e) {
return null;
}
})
.then(latest => {
if (latest && semver.lt(packageJson.version, latest)) {
console.log();
console.error(
chalk.yellow(
`You are running \`create-react-app\` ${packageJson.version}, which is behind the latest release (${latest}).\n\n` +
'We recommend always using the latest version of create-react-app if possible.'
)
);
console.log();
console.log(
'The latest instructions for creating a new app can be found here:\n' +
'https://create-react-app.dev/docs/getting-started/'
);
console.log();
} else {
const useYarn = isUsingYarn();
createApp(
projectName,
program.verbose,
program.scriptsVersion,
program.template,
useYarn,
program.usePnp
);
}
});
}
function createApp(name, verbose, version, template, useYarn, usePnp) {
const unsupportedNodeVersion = !semver.satisfies(
// Coerce strings with metadata (i.e. `15.0.0-nightly`).
semver.coerce(process.version),
'>=14'
);
if (unsupportedNodeVersion) {
console.log(
chalk.yellow(
`You are using Node ${process.version} so the project will be bootstrapped with an old unsupported version of tools.\n\n` +
`Please update to Node 14 or higher for a better, fully supported experience.\n`
)
);
// Fall back to latest supported react-scripts on Node 4
version = 'react-scripts@0.9.x';
}
const root = path.resolve(name);
const appName = path.basename(root);
checkAppName(appName);
fs.ensureDirSync(name);
if (!isSafeToCreateProjectIn(root, name)) {
process.exit(1);
}
console.log();
console.log(`Creating a new React app in ${chalk.green(root)}.`);
console.log();
const packageJson = {
name: appName,
version: '0.1.0',
private: true,
};
fs.writeFileSync(
path.join(root, 'package.json'),
JSON.stringify(packageJson, null, 2) + os.EOL
);
const originalDirectory = process.cwd();
process.chdir(root);
if (!useYarn && !checkThatNpmCanReadCwd()) {
process.exit(1);
}
if (!useYarn) {
const npmInfo = checkNpmVersion();
if (!npmInfo.hasMinNpm) {
if (npmInfo.npmVersion) {
console.log(
chalk.yellow(
`You are using npm ${npmInfo.npmVersion} so the project will be bootstrapped with an old unsupported version of tools.\n\n` +
`Please update to npm 6 or higher for a better, fully supported experience.\n`
)
);
}
// Fall back to latest supported react-scripts for npm 3
version = 'react-scripts@0.9.x';
}
} else if (usePnp) {
const yarnInfo = checkYarnVersion();
if (yarnInfo.yarnVersion) {
if (!yarnInfo.hasMinYarnPnp) {
console.log(
chalk.yellow(
`You are using Yarn ${yarnInfo.yarnVersion} together with the --use-pnp flag, but Plug'n'Play is only supported starting from the 1.12 release.\n\n` +
`Please update to Yarn 1.12 or higher for a better, fully supported experience.\n`
)
);
// 1.11 had an issue with webpack-dev-middleware, so better not use PnP with it (never reached stable, but still)
usePnp = false;
}
if (!yarnInfo.hasMaxYarnPnp) {
console.log(
chalk.yellow(
'The --use-pnp flag is no longer necessary with yarn 2 and will be deprecated and removed in a future release.\n'
)
);
// 2 supports PnP by default and breaks when trying to use the flag
usePnp = false;
}
}
}
run(
root,
appName,
version,
verbose,
originalDirectory,
template,
useYarn,
usePnp
);
}
function install(root, useYarn, usePnp, dependencies, verbose, isOnline) {
return new Promise((resolve, reject) => {
let command;
let args;
if (useYarn) {
command = 'yarnpkg';
args = ['add', '--exact'];
if (!isOnline) {
args.push('--offline');
}
if (usePnp) {
args.push('--enable-pnp');
}
[].push.apply(args, dependencies);
// Explicitly set cwd() to work around issues like
// https://github.com/facebook/create-react-app/issues/3326.
// Unfortunately we can only do this for Yarn because npm support for
// equivalent --prefix flag doesn't help with this issue.
// This is why for npm, we run checkThatNpmCanReadCwd() early instead.
args.push('--cwd');
args.push(root);
if (!isOnline) {
console.log(chalk.yellow('You appear to be offline.'));
console.log(chalk.yellow('Falling back to the local Yarn cache.'));
console.log();
}
} else {
command = 'npm';
args = [
'install',
'--no-audit', // https://github.com/facebook/create-react-app/issues/11174
'--save',
'--save-exact',
'--loglevel',
'error',
].concat(dependencies);
if (usePnp) {
console.log(chalk.yellow("NPM doesn't support PnP."));
console.log(chalk.yellow('Falling back to the regular installs.'));
console.log();
}
}
if (verbose) {
args.push('--verbose');
}
const child = spawn(command, args, { stdio: 'inherit' });
child.on('close', code => {
if (code !== 0) {
reject({
command: `${command} ${args.join(' ')}`,
});
return;
}
resolve();
});
});
}
function run(
root,
appName,
version,
verbose,
originalDirectory,
template,
useYarn,
usePnp
) {
Promise.all([
getInstallPackage(version, originalDirectory),
getTemplateInstallPackage(template, originalDirectory),
]).then(([packageToInstall, templateToInstall]) => {
const allDependencies = ['react', 'react-dom', packageToInstall];
console.log('Installing packages. This might take a couple of minutes.');
Promise.all([
getPackageInfo(packageToInstall),
getPackageInfo(templateToInstall),
])
.then(([packageInfo, templateInfo]) =>
checkIfOnline(useYarn).then(isOnline => ({
isOnline,
packageInfo,
templateInfo,
}))
)
.then(({ isOnline, packageInfo, templateInfo }) => {
let packageVersion = semver.coerce(packageInfo.version);
const templatesVersionMinimum = '3.3.0';
// Assume compatibility if we can't test the version.
if (!semver.valid(packageVersion)) {
packageVersion = templatesVersionMinimum;
}
// Only support templates when used alongside new react-scripts versions.
const supportsTemplates = semver.gte(
packageVersion,
templatesVersionMinimum
);
if (supportsTemplates) {
allDependencies.push(templateToInstall);
} else if (template) {
console.log('');
console.log(
`The ${chalk.cyan(packageInfo.name)} version you're using ${
packageInfo.name === 'react-scripts' ? 'is not' : 'may not be'
} compatible with the ${chalk.cyan('--template')} option.`
);
console.log('');
}
console.log(
`Installing ${chalk.cyan('react')}, ${chalk.cyan(
'react-dom'
)}, and ${chalk.cyan(packageInfo.name)}${
supportsTemplates ? ` with ${chalk.cyan(templateInfo.name)}` : ''
}...`
);
console.log();
return install(
root,
useYarn,
usePnp,
allDependencies,
verbose,
isOnline
).then(() => ({
packageInfo,
supportsTemplates,
templateInfo,
}));
})
.then(async ({ packageInfo, supportsTemplates, templateInfo }) => {
const packageName = packageInfo.name;
const templateName = supportsTemplates ? templateInfo.name : undefined;
checkNodeVersion(packageName);
setCaretRangeForRuntimeDeps(packageName);
const pnpPath = path.resolve(process.cwd(), '.pnp.js');
const nodeArgs = fs.existsSync(pnpPath) ? ['--require', pnpPath] : [];
await executeNodeScript(
{
cwd: process.cwd(),
args: nodeArgs,
},
[root, appName, verbose, originalDirectory, templateName],
`
const init = require('${packageName}/scripts/init.js');
init.apply(null, JSON.parse(process.argv[1]));
`
);
if (version === 'react-scripts@0.9.x') {
console.log(
chalk.yellow(
`\nNote: the project was bootstrapped with an old unsupported version of tools.\n` +
`Please update to Node >=14 and npm >=6 to get supported tools in new projects.\n`
)
);
}
})
.catch(reason => {
console.log();
console.log('Aborting installation.');
if (reason.command) {
console.log(` ${chalk.cyan(reason.command)} has failed.`);
} else {
console.log(
chalk.red('Unexpected error. Please report it as a bug:')
);
console.log(reason);
}
console.log();
// On 'exit' we will delete these files from target directory.
const knownGeneratedFiles = ['package.json', 'node_modules'];
const currentFiles = fs.readdirSync(path.join(root));
currentFiles.forEach(file => {
knownGeneratedFiles.forEach(fileToMatch => {
// This removes all knownGeneratedFiles.
if (file === fileToMatch) {
console.log(`Deleting generated file... ${chalk.cyan(file)}`);
fs.removeSync(path.join(root, file));
}
});
});
const remainingFiles = fs.readdirSync(path.join(root));
if (!remainingFiles.length) {
// Delete target folder if empty
console.log(
`Deleting ${chalk.cyan(`${appName}/`)} from ${chalk.cyan(
path.resolve(root, '..')
)}`
);
process.chdir(path.resolve(root, '..'));
fs.removeSync(path.join(root));
}
console.log('Done.');
process.exit(1);
});
});
}
function getInstallPackage(version, originalDirectory) {
let packageToInstall = 'react-scripts';
const validSemver = semver.valid(version);
if (validSemver) {
packageToInstall += `@${validSemver}`;
} else if (version) {
if (version[0] === '@' && !version.includes('/')) {
packageToInstall += version;
} else if (version.match(/^file:/)) {
packageToInstall = `file:${path.resolve(
originalDirectory,
version.match(/^file:(.*)?$/)[1]
)}`;
} else {
// for tar.gz or alternative paths
packageToInstall = version;
}
}
const scriptsToWarn = [
{
name: 'react-scripts-ts',
message: chalk.yellow(
`The react-scripts-ts package is deprecated. TypeScript is now supported natively in Create React App. You can use the ${chalk.green(
'--template typescript'
)} option instead when generating your app to include TypeScript support. Would you like to continue using react-scripts-ts?`
),
},
];
for (const script of scriptsToWarn) {
if (packageToInstall.startsWith(script.name)) {
return prompts({
type: 'confirm',
name: 'useScript',
message: script.message,
initial: false,
}).then(answer => {
if (!answer.useScript) {
process.exit(0);
}
return packageToInstall;
});
}
}
return Promise.resolve(packageToInstall);
}
function getTemplateInstallPackage(template, originalDirectory) {
let templateToInstall = 'cra-template';
if (template) {
if (template.match(/^file:/)) {
templateToInstall = `file:${path.resolve(
originalDirectory,
template.match(/^file:(.*)?$/)[1]
)}`;
} else if (
template.includes('://') ||
template.match(/^.+\.(tgz|tar\.gz)$/)
) {
// for tar.gz or alternative paths
templateToInstall = template;
} else {
// Add prefix 'cra-template-' to non-prefixed templates, leaving any
// @scope/ and @version intact.
const packageMatch = template.match(/^(@[^/]+\/)?([^@]+)?(@.+)?$/);
const scope = packageMatch[1] || '';
const templateName = packageMatch[2] || '';
const version = packageMatch[3] || '';
if (
templateName === templateToInstall ||
templateName.startsWith(`${templateToInstall}-`)
) {
// Covers:
// - cra-template
// - @SCOPE/cra-template
// - cra-template-NAME
// - @SCOPE/cra-template-NAME
templateToInstall = `${scope}${templateName}${version}`;
} else if (version && !scope && !templateName) {
// Covers using @SCOPE only
templateToInstall = `${version}/${templateToInstall}`;
} else {
// Covers templates without the `cra-template` prefix:
// - NAME
// - @SCOPE/NAME
templateToInstall = `${scope}${templateToInstall}-${templateName}${version}`;
}
}
}
return Promise.resolve(templateToInstall);
}
function getTemporaryDirectory() {
return new Promise((resolve, reject) => {
// Unsafe cleanup lets us recursively delete the directory if it contains
// contents; by default it only allows removal if it's empty
tmp.dir({ unsafeCleanup: true }, (err, tmpdir, callback) => {
if (err) {
reject(err);
} else {
resolve({
tmpdir: tmpdir,
cleanup: () => {
try {
callback();
} catch (ignored) {
// Callback might throw and fail, since it's a temp directory the
// OS will clean it up eventually...
}
},
});
}
});
});
}
function extractStream(stream, dest) {
return new Promise((resolve, reject) => {
stream.pipe(
unpack(dest, err => {
if (err) {
reject(err);
} else {
resolve(dest);
}
})
);
});
}
// Extract package name from tarball url or path.
function getPackageInfo(installPackage) {
if (installPackage.match(/^.+\.(tgz|tar\.gz)$/)) {
return getTemporaryDirectory()
.then(obj => {
let stream;
if (/^http/.test(installPackage)) {
stream = hyperquest(installPackage);
} else {
stream = fs.createReadStream(installPackage);
}
return extractStream(stream, obj.tmpdir).then(() => obj);
})
.then(obj => {
const { name, version } = require(path.join(
obj.tmpdir,
'package.json'
));
obj.cleanup();
return { name, version };
})
.catch(err => {
// The package name could be with or without semver version, e.g. react-scripts-0.2.0-alpha.1.tgz
// However, this function returns package name only without semver version.
console.log(
`Could not extract the package name from the archive: ${err.message}`
);
const assumedProjectName = installPackage.match(
/^.+\/(.+?)(?:-\d+.+)?\.(tgz|tar\.gz)$/
)[1];
console.log(
`Based on the filename, assuming it is "${chalk.cyan(
assumedProjectName
)}"`
);
return Promise.resolve({ name: assumedProjectName });
});
} else if (installPackage.startsWith('git+')) {
// Pull package name out of git urls e.g:
// git+https://github.com/mycompany/react-scripts.git
// git+ssh://github.com/mycompany/react-scripts.git#v1.2.3
return Promise.resolve({
name: installPackage.match(/([^/]+)\.git(#.*)?$/)[1],
});
} else if (installPackage.match(/.+@/)) {
// Do not match @scope/ when stripping off @version or @tag
return Promise.resolve({
name: installPackage.charAt(0) + installPackage.substr(1).split('@')[0],
version: installPackage.split('@')[1],
});
} else if (installPackage.match(/^file:/)) {
const installPackagePath = installPackage.match(/^file:(.*)?$/)[1];
const { name, version } = require(path.join(
installPackagePath,
'package.json'
));
return Promise.resolve({ name, version });
}
return Promise.resolve({ name: installPackage });
}
function checkNpmVersion() {
let hasMinNpm = false;
let npmVersion = null;
try {
npmVersion = execSync('npm --version').toString().trim();
hasMinNpm = semver.gte(npmVersion, '6.0.0');
} catch (err) {
// ignore
}
return {
hasMinNpm: hasMinNpm,
npmVersion: npmVersion,
};
}
function checkYarnVersion() {
const minYarnPnp = '1.12.0';
const maxYarnPnp = '2.0.0';
let hasMinYarnPnp = false;
let hasMaxYarnPnp = false;
let yarnVersion = null;
try {
yarnVersion = execSync('yarnpkg --version').toString().trim();
if (semver.valid(yarnVersion)) {
hasMinYarnPnp = semver.gte(yarnVersion, minYarnPnp);
hasMaxYarnPnp = semver.lt(yarnVersion, maxYarnPnp);
} else {
// Handle non-semver compliant yarn version strings, which yarn currently
// uses for nightly builds. The regex truncates anything after the first
// dash. See #5362.
const trimmedYarnVersionMatch = /^(.+?)[-+].+$/.exec(yarnVersion);
if (trimmedYarnVersionMatch) {
const trimmedYarnVersion = trimmedYarnVersionMatch.pop();
hasMinYarnPnp = semver.gte(trimmedYarnVersion, minYarnPnp);
hasMaxYarnPnp = semver.lt(trimmedYarnVersion, maxYarnPnp);
}
}
} catch (err) {
// ignore
}
return {
hasMinYarnPnp: hasMinYarnPnp,
hasMaxYarnPnp: hasMaxYarnPnp,
yarnVersion: yarnVersion,
};
}
function checkNodeVersion(packageName) {
const packageJsonPath = path.resolve(
process.cwd(),
'node_modules',
packageName,
'package.json'
);
if (!fs.existsSync(packageJsonPath)) {
return;
}
const packageJson = require(packageJsonPath);
if (!packageJson.engines || !packageJson.engines.node) {
return;
}
if (!semver.satisfies(process.version, packageJson.engines.node)) {
console.error(
chalk.red(
'You are running Node %s.\n' +
'Create React App requires Node %s or higher. \n' +
'Please update your version of Node.'
),
process.version,
packageJson.engines.node
);
process.exit(1);
}
}
function checkAppName(appName) {
const validationResult = validateProjectName(appName);
if (!validationResult.validForNewPackages) {
console.error(
chalk.red(
`Cannot create a project named ${chalk.green(
`"${appName}"`
)} because of npm naming restrictions:\n`
)
);
[
...(validationResult.errors || []),
...(validationResult.warnings || []),
].forEach(error => {
console.error(chalk.red(` * ${error}`));
});
console.error(chalk.red('\nPlease choose a different project name.'));
process.exit(1);
}
// TODO: there should be a single place that holds the dependencies
const dependencies = ['react', 'react-dom', 'react-scripts'].sort();
if (dependencies.includes(appName)) {
console.error(
chalk.red(
`Cannot create a project named ${chalk.green(
`"${appName}"`
)} because a dependency with the same name exists.\n` +
`Due to the way npm works, the following names are not allowed:\n\n`
) +
chalk.cyan(dependencies.map(depName => ` ${depName}`).join('\n')) +
chalk.red('\n\nPlease choose a different project name.')
);
process.exit(1);
}
}
function makeCaretRange(dependencies, name) {
const version = dependencies[name];
if (typeof version === 'undefined') {
console.error(chalk.red(`Missing ${name} dependency in package.json`));
process.exit(1);
}
let patchedVersion = `^${version}`;
if (!semver.validRange(patchedVersion)) {
console.error(
`Unable to patch ${name} dependency version because version ${chalk.red(
version
)} will become invalid ${chalk.red(patchedVersion)}`
);
patchedVersion = version;
}
dependencies[name] = patchedVersion;
}
function setCaretRangeForRuntimeDeps(packageName) {
const packagePath = path.join(process.cwd(), 'package.json');
const packageJson = require(packagePath);
if (typeof packageJson.dependencies === 'undefined') {
console.error(chalk.red('Missing dependencies in package.json'));
process.exit(1);
}
const packageVersion = packageJson.dependencies[packageName];
if (typeof packageVersion === 'undefined') {
console.error(chalk.red(`Unable to find ${packageName} in package.json`));
process.exit(1);
}
makeCaretRange(packageJson.dependencies, 'react');
makeCaretRange(packageJson.dependencies, 'react-dom');
fs.writeFileSync(packagePath, JSON.stringify(packageJson, null, 2) + os.EOL);
}
// If project only contains files generated by GH, it’s safe.
// Also, if project contains remnant error logs from a previous
// installation, lets remove them now.
// We also special case IJ-based products .idea because it integrates with CRA:
// https://github.com/facebook/create-react-app/pull/368#issuecomment-243446094
function isSafeToCreateProjectIn(root, name) {
const validFiles = [
'.DS_Store',
'.git',
'.gitattributes',
'.gitignore',
'.gitlab-ci.yml',
'.hg',
'.hgcheck',
'.hgignore',
'.idea',
'.npmignore',
'.travis.yml',
'docs',
'LICENSE',
'README.md',
'mkdocs.yml',
'Thumbs.db',
];
// These files should be allowed to remain on a failed install, but then
// silently removed during the next create.
const errorLogFilePatterns = [
'npm-debug.log',
'yarn-error.log',
'yarn-debug.log',
];
const isErrorLog = file => {
return errorLogFilePatterns.some(pattern => file.startsWith(pattern));
};
const conflicts = fs
.readdirSync(root)
.filter(file => !validFiles.includes(file))
// IntelliJ IDEA creates module files before CRA is launched
.filter(file => !/\.iml$/.test(file))
// Don't treat log files from previous installation as conflicts
.filter(file => !isErrorLog(file));
if (conflicts.length > 0) {
console.log(
`The directory ${chalk.green(name)} contains files that could conflict:`
);
console.log();
for (const file of conflicts) {
try {
const stats = fs.lstatSync(path.join(root, file));
if (stats.isDirectory()) {
console.log(` ${chalk.blue(`${file}/`)}`);
} else {
console.log(` ${file}`);
}
} catch (e) {
console.log(` ${file}`);
}
}
console.log();
console.log(
'Either try using a new directory name, or remove the files listed above.'
);
return false;
}
// Remove any log files from a previous installation.
fs.readdirSync(root).forEach(file => {
if (isErrorLog(file)) {
fs.removeSync(path.join(root, file));
}
});
return true;
}
function getProxy() {
if (process.env.https_proxy) {
return process.env.https_proxy;
} else {
try {
// Trying to read https-proxy from .npmrc
let httpsProxy = execSync('npm config get https-proxy').toString().trim();
return httpsProxy !== 'null' ? httpsProxy : undefined;
} catch (e) {
return;
}
}
}
// See https://github.com/facebook/create-react-app/pull/3355
function checkThatNpmCanReadCwd() {
const cwd = process.cwd();
let childOutput = null;
try {
// Note: intentionally using spawn over exec since
// the problem doesn't reproduce otherwise.
// `npm config list` is the only reliable way I could find
// to reproduce the wrong path. Just printing process.cwd()
// in a Node process was not enough.
childOutput = spawn.sync('npm', ['config', 'list']).output.join('');
} catch (err) {
// Something went wrong spawning node.
// Not great, but it means we can't do this check.
// We might fail later on, but let's continue.
return true;
}
if (typeof childOutput !== 'string') {
return true;
}
const lines = childOutput.split('\n');
// `npm config list` output includes the following line:
// "; cwd = C:\path\to\current\dir" (unquoted)
// I couldn't find an easier way to get it.
const prefix = '; cwd = ';
const line = lines.find(line => line.startsWith(prefix));
if (typeof line !== 'string') {
// Fail gracefully. They could remove it.
return true;
}
const npmCWD = line.substring(prefix.length);
if (npmCWD === cwd) {
return true;
}
console.error(
chalk.red(
`Could not start an npm process in the right directory.\n\n` +
`The current directory is: ${chalk.bold(cwd)}\n` +
`However, a newly started npm process runs in: ${chalk.bold(
npmCWD
)}\n\n` +
`This is probably caused by a misconfigured system terminal shell.`
)
);
if (process.platform === 'win32') {
console.error(
chalk.red(`On Windows, this can usually be fixed by running:\n\n`) +
` ${chalk.cyan(
'reg'
)} delete "HKCU\\Software\\Microsoft\\Command Processor" /v AutoRun /f\n` +
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | true |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/create-react-app/__tests__/getTemplateInstallPackage.test.js | packages/create-react-app/__tests__/getTemplateInstallPackage.test.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
const { getTemplateInstallPackage } = require('../createReactApp');
describe('getTemplateInstallPackage', () => {
it('no options gives cra-template', async () => {
await expect(getTemplateInstallPackage()).resolves.toBe('cra-template');
});
it('cra-template gives cra-template', async () => {
await expect(getTemplateInstallPackage('cra-template')).resolves.toBe(
'cra-template'
);
});
it('cra-template-typescript gives cra-template-typescript', async () => {
await expect(
getTemplateInstallPackage('cra-template-typescript')
).resolves.toBe('cra-template-typescript');
});
it('typescript gives cra-template-typescript', async () => {
await expect(getTemplateInstallPackage('typescript')).resolves.toBe(
'cra-template-typescript'
);
});
it('typescript@next gives cra-template-typescript@next', async () => {
await expect(getTemplateInstallPackage('typescript@next')).resolves.toBe(
'cra-template-typescript@next'
);
});
it('cra-template@next gives cra-template@next', async () => {
await expect(getTemplateInstallPackage('cra-template@next')).resolves.toBe(
'cra-template@next'
);
});
it('cra-template-typescript@next gives cra-template-typescript@next', async () => {
await expect(
getTemplateInstallPackage('cra-template-typescript@next')
).resolves.toBe('cra-template-typescript@next');
});
it('@iansu gives @iansu/cra-template', async () => {
await expect(getTemplateInstallPackage('@iansu')).resolves.toBe(
'@iansu/cra-template'
);
});
it('@iansu/cra-template gives @iansu/cra-template', async () => {
await expect(
getTemplateInstallPackage('@iansu/cra-template')
).resolves.toBe('@iansu/cra-template');
});
it('@iansu/cra-template@next gives @iansu/cra-template@next', async () => {
await expect(
getTemplateInstallPackage('@iansu/cra-template@next')
).resolves.toBe('@iansu/cra-template@next');
});
it('@iansu/cra-template-typescript@next gives @iansu/cra-template-typescript@next', async () => {
await expect(
getTemplateInstallPackage('@iansu/cra-template-typescript@next')
).resolves.toBe('@iansu/cra-template-typescript@next');
});
it('http://example.com/cra-template.tar.gz gives http://example.com/cra-template.tar.gz', async () => {
await expect(
getTemplateInstallPackage('http://example.com/cra-template.tar.gz')
).resolves.toBe('http://example.com/cra-template.tar.gz');
});
});
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-scripts/scripts/start.js | packages/react-scripts/scripts/start.js | // @remove-on-eject-begin
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
// @remove-on-eject-end
'use strict';
// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'development';
process.env.NODE_ENV = 'development';
// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => {
throw err;
});
// Ensure environment variables are read.
require('../config/env');
const fs = require('fs');
const chalk = require('react-dev-utils/chalk');
const webpack = require('webpack');
const WebpackDevServer = require('webpack-dev-server');
const clearConsole = require('react-dev-utils/clearConsole');
const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
const {
choosePort,
createCompiler,
prepareProxy,
prepareUrls,
} = require('react-dev-utils/WebpackDevServerUtils');
const openBrowser = require('react-dev-utils/openBrowser');
const semver = require('semver');
const paths = require('../config/paths');
const configFactory = require('../config/webpack.config');
const createDevServerConfig = require('../config/webpackDevServer.config');
const getClientEnvironment = require('../config/env');
const react = require(require.resolve('react', { paths: [paths.appPath] }));
const env = getClientEnvironment(paths.publicUrlOrPath.slice(0, -1));
const useYarn = fs.existsSync(paths.yarnLockFile);
const isInteractive = process.stdout.isTTY;
// Warn and crash if required files are missing
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
process.exit(1);
}
// Tools like Cloud9 rely on this.
const DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3000;
const HOST = process.env.HOST || '0.0.0.0';
if (process.env.HOST) {
console.log(
chalk.cyan(
`Attempting to bind to HOST environment variable: ${chalk.yellow(
chalk.bold(process.env.HOST)
)}`
)
);
console.log(
`If this was unintentional, check that you haven't mistakenly set it in your shell.`
);
console.log(
`Learn more here: ${chalk.yellow('https://cra.link/advanced-config')}`
);
console.log();
}
// We require that you explicitly set browsers and do not fall back to
// browserslist defaults.
const { checkBrowsers } = require('react-dev-utils/browsersHelper');
checkBrowsers(paths.appPath, isInteractive)
.then(() => {
// We attempt to use the default port but if it is busy, we offer the user to
// run on a different port. `choosePort()` Promise resolves to the next free port.
return choosePort(HOST, DEFAULT_PORT);
})
.then(port => {
if (port == null) {
// We have not found a port.
return;
}
const config = configFactory('development');
const protocol = process.env.HTTPS === 'true' ? 'https' : 'http';
const appName = require(paths.appPackageJson).name;
const useTypeScript = fs.existsSync(paths.appTsConfig);
const urls = prepareUrls(
protocol,
HOST,
port,
paths.publicUrlOrPath.slice(0, -1)
);
// Create a webpack compiler that is configured with custom messages.
const compiler = createCompiler({
appName,
config,
urls,
useYarn,
useTypeScript,
webpack,
});
// Load proxy config
const proxySetting = require(paths.appPackageJson).proxy;
const proxyConfig = prepareProxy(
proxySetting,
paths.appPublic,
paths.publicUrlOrPath
);
// Serve webpack assets generated by the compiler over a web server.
const serverConfig = {
...createDevServerConfig(proxyConfig, urls.lanUrlForConfig),
host: HOST,
port,
};
const devServer = new WebpackDevServer(serverConfig, compiler);
// Launch WebpackDevServer.
devServer.startCallback(() => {
if (isInteractive) {
clearConsole();
}
if (env.raw.FAST_REFRESH && semver.lt(react.version, '16.10.0')) {
console.log(
chalk.yellow(
`Fast Refresh requires React 16.10 or higher. You are using React ${react.version}.`
)
);
}
console.log(chalk.cyan('Starting the development server...\n'));
openBrowser(urls.localUrlForBrowser);
});
['SIGINT', 'SIGTERM'].forEach(function (sig) {
process.on(sig, function () {
devServer.close();
process.exit();
});
});
if (process.env.CI !== 'true') {
// Gracefully exit when stdin ends
process.stdin.on('end', function () {
devServer.close();
process.exit();
});
}
})
.catch(err => {
if (err && err.message) {
console.log(err.message);
}
process.exit(1);
});
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-scripts/scripts/test.js | packages/react-scripts/scripts/test.js | // @remove-on-eject-begin
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
// @remove-on-eject-end
'use strict';
// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'test';
process.env.NODE_ENV = 'test';
process.env.PUBLIC_URL = '';
// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => {
throw err;
});
// Ensure environment variables are read.
require('../config/env');
const jest = require('jest');
const execSync = require('child_process').execSync;
let argv = process.argv.slice(2);
function isInGitRepository() {
try {
execSync('git rev-parse --is-inside-work-tree', { stdio: 'ignore' });
return true;
} catch (e) {
return false;
}
}
function isInMercurialRepository() {
try {
execSync('hg --cwd . root', { stdio: 'ignore' });
return true;
} catch (e) {
return false;
}
}
// Watch unless on CI or explicitly running all tests
if (
!process.env.CI &&
argv.indexOf('--watchAll') === -1 &&
argv.indexOf('--watchAll=false') === -1
) {
// https://github.com/facebook/create-react-app/issues/5210
const hasSourceControl = isInGitRepository() || isInMercurialRepository();
argv.push(hasSourceControl ? '--watch' : '--watchAll');
}
// @remove-on-eject-begin
// This is not necessary after eject because we embed config into package.json.
const createJestConfig = require('./utils/createJestConfig');
const path = require('path');
const paths = require('../config/paths');
argv.push(
'--config',
JSON.stringify(
createJestConfig(
relativePath => path.resolve(__dirname, '..', relativePath),
path.resolve(paths.appSrc, '..'),
false
)
)
);
// This is a very dirty workaround for https://github.com/facebook/jest/issues/5913.
// We're trying to resolve the environment ourselves because Jest does it incorrectly.
// TODO: remove this as soon as it's fixed in Jest.
const resolve = require('resolve');
function resolveJestDefaultEnvironment(name) {
const jestDir = path.dirname(
resolve.sync('jest', {
basedir: __dirname,
})
);
const jestCLIDir = path.dirname(
resolve.sync('jest-cli', {
basedir: jestDir,
})
);
const jestConfigDir = path.dirname(
resolve.sync('jest-config', {
basedir: jestCLIDir,
})
);
return resolve.sync(name, {
basedir: jestConfigDir,
});
}
let cleanArgv = [];
let env = 'jsdom';
let next;
do {
next = argv.shift();
if (next === '--env') {
env = argv.shift();
} else if (next.indexOf('--env=') === 0) {
env = next.substring('--env='.length);
} else {
cleanArgv.push(next);
}
} while (argv.length > 0);
argv = cleanArgv;
let resolvedEnv;
try {
resolvedEnv = resolveJestDefaultEnvironment(`jest-environment-${env}`);
} catch (e) {
// ignore
}
if (!resolvedEnv) {
try {
resolvedEnv = resolveJestDefaultEnvironment(env);
} catch (e) {
// ignore
}
}
const testEnvironment = resolvedEnv || env;
argv.push('--env', testEnvironment);
// @remove-on-eject-end
jest.run(argv);
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-scripts/scripts/build.js | packages/react-scripts/scripts/build.js | // @remove-on-eject-begin
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
// @remove-on-eject-end
'use strict';
// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'production';
process.env.NODE_ENV = 'production';
// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => {
throw err;
});
// Ensure environment variables are read.
require('../config/env');
const path = require('path');
const chalk = require('react-dev-utils/chalk');
const fs = require('fs-extra');
const bfj = require('bfj');
const webpack = require('webpack');
const configFactory = require('../config/webpack.config');
const paths = require('../config/paths');
const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
const formatWebpackMessages = require('react-dev-utils/formatWebpackMessages');
const printHostingInstructions = require('react-dev-utils/printHostingInstructions');
const FileSizeReporter = require('react-dev-utils/FileSizeReporter');
const printBuildError = require('react-dev-utils/printBuildError');
const measureFileSizesBeforeBuild =
FileSizeReporter.measureFileSizesBeforeBuild;
const printFileSizesAfterBuild = FileSizeReporter.printFileSizesAfterBuild;
const useYarn = fs.existsSync(paths.yarnLockFile);
// These sizes are pretty large. We'll warn for bundles exceeding them.
const WARN_AFTER_BUNDLE_GZIP_SIZE = 512 * 1024;
const WARN_AFTER_CHUNK_GZIP_SIZE = 1024 * 1024;
const isInteractive = process.stdout.isTTY;
// Warn and crash if required files are missing
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
process.exit(1);
}
const argv = process.argv.slice(2);
const writeStatsJson = argv.indexOf('--stats') !== -1;
// Generate configuration
const config = configFactory('production');
// We require that you explicitly set browsers and do not fall back to
// browserslist defaults.
const { checkBrowsers } = require('react-dev-utils/browsersHelper');
checkBrowsers(paths.appPath, isInteractive)
.then(() => {
// First, read the current file sizes in build directory.
// This lets us display how much they changed later.
return measureFileSizesBeforeBuild(paths.appBuild);
})
.then(previousFileSizes => {
// Remove all content but keep the directory so that
// if you're in it, you don't end up in Trash
fs.emptyDirSync(paths.appBuild);
// Merge with the public folder
copyPublicFolder();
// Start the webpack build
return build(previousFileSizes);
})
.then(
({ stats, previousFileSizes, warnings }) => {
if (warnings.length) {
console.log(chalk.yellow('Compiled with warnings.\n'));
console.log(warnings.join('\n\n'));
console.log(
'\nSearch for the ' +
chalk.underline(chalk.yellow('keywords')) +
' to learn more about each warning.'
);
console.log(
'To ignore, add ' +
chalk.cyan('// eslint-disable-next-line') +
' to the line before.\n'
);
} else {
console.log(chalk.green('Compiled successfully.\n'));
}
console.log('File sizes after gzip:\n');
printFileSizesAfterBuild(
stats,
previousFileSizes,
paths.appBuild,
WARN_AFTER_BUNDLE_GZIP_SIZE,
WARN_AFTER_CHUNK_GZIP_SIZE
);
console.log();
const appPackage = require(paths.appPackageJson);
const publicUrl = paths.publicUrlOrPath;
const publicPath = config.output.publicPath;
const buildFolder = path.relative(process.cwd(), paths.appBuild);
printHostingInstructions(
appPackage,
publicUrl,
publicPath,
buildFolder,
useYarn
);
},
err => {
const tscCompileOnError = process.env.TSC_COMPILE_ON_ERROR === 'true';
if (tscCompileOnError) {
console.log(
chalk.yellow(
'Compiled with the following type errors (you may want to check these before deploying your app):\n'
)
);
printBuildError(err);
} else {
console.log(chalk.red('Failed to compile.\n'));
printBuildError(err);
process.exit(1);
}
}
)
.catch(err => {
if (err && err.message) {
console.log(err.message);
}
process.exit(1);
});
// Create the production build and print the deployment instructions.
function build(previousFileSizes) {
console.log('Creating an optimized production build...');
const compiler = webpack(config);
return new Promise((resolve, reject) => {
compiler.run((err, stats) => {
let messages;
if (err) {
if (!err.message) {
return reject(err);
}
let errMessage = err.message;
// Add additional information for postcss errors
if (Object.prototype.hasOwnProperty.call(err, 'postcssNode')) {
errMessage +=
'\nCompileError: Begins at CSS selector ' +
err['postcssNode'].selector;
}
messages = formatWebpackMessages({
errors: [errMessage],
warnings: [],
});
} else {
messages = formatWebpackMessages(
stats.toJson({ all: false, warnings: true, errors: true })
);
}
if (messages.errors.length) {
// Only keep the first error. Others are often indicative
// of the same problem, but confuse the reader with noise.
if (messages.errors.length > 1) {
messages.errors.length = 1;
}
return reject(new Error(messages.errors.join('\n\n')));
}
if (
process.env.CI &&
(typeof process.env.CI !== 'string' ||
process.env.CI.toLowerCase() !== 'false') &&
messages.warnings.length
) {
// Ignore sourcemap warnings in CI builds. See #8227 for more info.
const filteredWarnings = messages.warnings.filter(
w => !/Failed to parse source map/.test(w)
);
if (filteredWarnings.length) {
console.log(
chalk.yellow(
'\nTreating warnings as errors because process.env.CI = true.\n' +
'Most CI servers set it automatically.\n'
)
);
return reject(new Error(filteredWarnings.join('\n\n')));
}
}
const resolveArgs = {
stats,
previousFileSizes,
warnings: messages.warnings,
};
if (writeStatsJson) {
return bfj
.write(paths.appBuild + '/bundle-stats.json', stats.toJson())
.then(() => resolve(resolveArgs))
.catch(error => reject(new Error(error)));
}
return resolve(resolveArgs);
});
});
}
function copyPublicFolder() {
fs.copySync(paths.appPublic, paths.appBuild, {
dereference: true,
filter: file => file !== paths.appHtml,
});
}
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-scripts/scripts/eject.js | packages/react-scripts/scripts/eject.js | // @remove-file-on-eject
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => {
throw err;
});
const fs = require('fs-extra');
const path = require('path');
const prompts = require('prompts');
const execSync = require('child_process').execSync;
const chalk = require('react-dev-utils/chalk');
const paths = require('../config/paths');
const createJestConfig = require('./utils/createJestConfig');
const spawnSync = require('react-dev-utils/crossSpawn').sync;
const os = require('os');
const green = chalk.green;
const cyan = chalk.cyan;
function getGitStatus() {
try {
let stdout = execSync(`git status --porcelain`, {
stdio: ['pipe', 'pipe', 'ignore'],
}).toString();
return stdout.trim();
} catch (e) {
return '';
}
}
function tryGitAdd(appPath) {
try {
spawnSync(
'git',
['add', path.join(appPath, 'config'), path.join(appPath, 'scripts')],
{
stdio: 'inherit',
}
);
return true;
} catch (e) {
return false;
}
}
console.log(
chalk.cyan.bold(
'NOTE: Create React App 2+ supports TypeScript, Sass, CSS Modules and more without ejecting: ' +
'https://reactjs.org/blog/2018/10/01/create-react-app-v2.html'
)
);
console.log();
prompts({
type: 'confirm',
name: 'shouldEject',
message: 'Are you sure you want to eject? This action is permanent.',
initial: false,
}).then(answer => {
if (!answer.shouldEject) {
console.log(cyan('Close one! Eject aborted.'));
return;
}
const gitStatus = getGitStatus();
if (gitStatus) {
console.error(
chalk.red(
'This git repository has untracked files or uncommitted changes:'
) +
'\n\n' +
gitStatus
.split('\n')
.map(line => line.match(/ .*/g)[0].trim())
.join('\n') +
'\n\n' +
chalk.red(
'Remove untracked files, stash or commit any changes, and try again.'
)
);
process.exit(1);
}
console.log('Ejecting...');
const ownPath = paths.ownPath;
const appPath = paths.appPath;
function verifyAbsent(file) {
if (fs.existsSync(path.join(appPath, file))) {
console.error(
`\`${file}\` already exists in your app folder. We cannot ` +
'continue as you would lose all the changes in that file or directory. ' +
'Please move or delete it (maybe make a copy for backup) and run this ' +
'command again.'
);
process.exit(1);
}
}
const folders = [
'config',
'config/jest',
'scripts',
'config/webpack/persistentCache',
];
// Make shallow array of files paths
const files = folders.reduce((files, folder) => {
return files.concat(
fs
.readdirSync(path.join(ownPath, folder))
// set full path
.map(file => path.join(ownPath, folder, file))
// omit dirs from file list
.filter(file => fs.lstatSync(file).isFile())
);
}, []);
// Ensure that the app folder is clean and we won't override any files
folders.forEach(verifyAbsent);
files.forEach(verifyAbsent);
// Prepare Jest config early in case it throws
const jestConfig = createJestConfig(
filePath => path.posix.join('<rootDir>', filePath),
null,
true
);
console.log();
console.log(cyan(`Copying files into ${appPath}`));
folders.forEach(folder => {
fs.mkdirSync(path.join(appPath, folder), { recursive: true });
});
files.forEach(file => {
let content = fs.readFileSync(file, 'utf8');
// Skip flagged files
if (content.match(/\/\/ @remove-file-on-eject/)) {
return;
}
content =
content
// Remove dead code from .js files on eject
.replace(
/\/\/ @remove-on-eject-begin([\s\S]*?)\/\/ @remove-on-eject-end/gm,
''
)
// Remove dead code from .applescript files on eject
.replace(
/-- @remove-on-eject-begin([\s\S]*?)-- @remove-on-eject-end/gm,
''
)
.trim() + '\n';
console.log(` Adding ${cyan(file.replace(ownPath, ''))} to the project`);
fs.writeFileSync(file.replace(ownPath, appPath), content);
});
console.log();
const ownPackage = require(path.join(ownPath, 'package.json'));
const appPackage = require(path.join(appPath, 'package.json'));
console.log(cyan('Updating the dependencies'));
const ownPackageName = ownPackage.name;
if (appPackage.devDependencies) {
// We used to put react-scripts in devDependencies
if (appPackage.devDependencies[ownPackageName]) {
console.log(` Removing ${cyan(ownPackageName)} from devDependencies`);
delete appPackage.devDependencies[ownPackageName];
}
}
appPackage.dependencies = appPackage.dependencies || {};
if (appPackage.dependencies[ownPackageName]) {
console.log(` Removing ${cyan(ownPackageName)} from dependencies`);
delete appPackage.dependencies[ownPackageName];
}
Object.keys(ownPackage.dependencies).forEach(key => {
// For some reason optionalDependencies end up in dependencies after install
if (
ownPackage.optionalDependencies &&
ownPackage.optionalDependencies[key]
) {
return;
}
console.log(` Adding ${cyan(key)} to dependencies`);
appPackage.dependencies[key] = ownPackage.dependencies[key];
});
// Sort the deps
const unsortedDependencies = appPackage.dependencies;
appPackage.dependencies = {};
Object.keys(unsortedDependencies)
.sort()
.forEach(key => {
appPackage.dependencies[key] = unsortedDependencies[key];
});
console.log();
console.log(cyan('Updating the scripts'));
delete appPackage.scripts['eject'];
Object.keys(appPackage.scripts).forEach(key => {
Object.keys(ownPackage.bin).forEach(binKey => {
const regex = new RegExp(binKey + ' (\\w+)', 'g');
if (!regex.test(appPackage.scripts[key])) {
return;
}
appPackage.scripts[key] = appPackage.scripts[key].replace(
regex,
'node scripts/$1.js'
);
console.log(
` Replacing ${cyan(`"${binKey} ${key}"`)} with ${cyan(
`"node scripts/${key}.js"`
)}`
);
});
});
console.log();
console.log(cyan('Configuring package.json'));
// Add Jest config
console.log(` Adding ${cyan('Jest')} configuration`);
appPackage.jest = jestConfig;
// Add Babel config
console.log(` Adding ${cyan('Babel')} preset`);
appPackage.babel = {
presets: ['react-app'],
};
// Add ESlint config
if (!appPackage.eslintConfig) {
console.log(` Adding ${cyan('ESLint')} configuration`);
appPackage.eslintConfig = {
extends: 'react-app',
};
}
fs.writeFileSync(
path.join(appPath, 'package.json'),
JSON.stringify(appPackage, null, 2) + os.EOL
);
console.log();
if (fs.existsSync(paths.appTypeDeclarations)) {
try {
// Read app declarations file
let content = fs.readFileSync(paths.appTypeDeclarations, 'utf8');
const ownContent =
fs.readFileSync(paths.ownTypeDeclarations, 'utf8').trim() + os.EOL;
// Remove react-scripts reference since they're getting a copy of the types in their project
content =
content
// Remove react-scripts types
.replace(
/^\s*\/\/\/\s*<reference\s+types.+?"react-scripts".*\/>.*(?:\n|$)/gm,
''
)
.trim() + os.EOL;
fs.writeFileSync(
paths.appTypeDeclarations,
(ownContent + os.EOL + content).trim() + os.EOL
);
} catch (e) {
// It's not essential that this succeeds, the TypeScript user should
// be able to re-create these types with ease.
}
}
// "Don't destroy what isn't ours"
if (ownPath.indexOf(appPath) === 0) {
try {
// remove react-scripts and react-scripts binaries from app node_modules
Object.keys(ownPackage.bin).forEach(binKey => {
fs.removeSync(path.join(appPath, 'node_modules', '.bin', binKey));
});
fs.removeSync(ownPath);
} catch (e) {
// It's not essential that this succeeds
}
}
if (fs.existsSync(paths.yarnLockFile)) {
const windowsCmdFilePath = path.join(
appPath,
'node_modules',
'.bin',
'react-scripts.cmd'
);
let windowsCmdFileContent;
if (process.platform === 'win32') {
// https://github.com/facebook/create-react-app/pull/3806#issuecomment-357781035
// Yarn is diligent about cleaning up after itself, but this causes the react-scripts.cmd file
// to be deleted while it is running. This trips Windows up after the eject completes.
// We'll read the batch file and later "write it back" to match npm behavior.
try {
windowsCmdFileContent = fs.readFileSync(windowsCmdFilePath);
} catch (err) {
// If this fails we're not worse off than if we didn't try to fix it.
}
}
console.log(cyan('Running yarn...'));
spawnSync('yarnpkg', ['--cwd', process.cwd()], { stdio: 'inherit' });
if (windowsCmdFileContent && !fs.existsSync(windowsCmdFilePath)) {
try {
fs.writeFileSync(windowsCmdFilePath, windowsCmdFileContent);
} catch (err) {
// If this fails we're not worse off than if we didn't try to fix it.
}
}
} else {
console.log(cyan('Running npm install...'));
spawnSync('npm', ['install', '--loglevel', 'error'], {
stdio: 'inherit',
});
}
console.log(green('Ejected successfully!'));
console.log();
if (tryGitAdd(appPath)) {
console.log(cyan('Staged ejected files for commit.'));
console.log();
}
console.log(green('Please consider sharing why you ejected in this survey:'));
console.log(green(' http://goo.gl/forms/Bi6CZjk1EqsdelXk1'));
console.log();
});
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-scripts/scripts/init.js | packages/react-scripts/scripts/init.js | // @remove-file-on-eject
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => {
throw err;
});
const fs = require('fs-extra');
const path = require('path');
const chalk = require('react-dev-utils/chalk');
const execSync = require('child_process').execSync;
const spawn = require('react-dev-utils/crossSpawn');
const { defaultBrowsers } = require('react-dev-utils/browsersHelper');
const os = require('os');
const verifyTypeScriptSetup = require('./utils/verifyTypeScriptSetup');
function isInGitRepository() {
try {
execSync('git rev-parse --is-inside-work-tree', { stdio: 'ignore' });
return true;
} catch (e) {
return false;
}
}
function isInMercurialRepository() {
try {
execSync('hg --cwd . root', { stdio: 'ignore' });
return true;
} catch (e) {
return false;
}
}
function tryGitInit() {
try {
execSync('git --version', { stdio: 'ignore' });
if (isInGitRepository() || isInMercurialRepository()) {
return false;
}
execSync('git init', { stdio: 'ignore' });
return true;
} catch (e) {
console.warn('Git repo not initialized', e);
return false;
}
}
function tryGitCommit(appPath) {
try {
execSync('git add -A', { stdio: 'ignore' });
execSync('git commit -m "Initialize project using Create React App"', {
stdio: 'ignore',
});
return true;
} catch (e) {
// We couldn't commit in already initialized git repo,
// maybe the commit author config is not set.
// In the future, we might supply our own committer
// like Ember CLI does, but for now, let's just
// remove the Git files to avoid a half-done state.
console.warn('Git commit not created', e);
console.warn('Removing .git directory...');
try {
// unlinkSync() doesn't work on directories.
fs.removeSync(path.join(appPath, '.git'));
} catch (removeErr) {
// Ignore.
}
return false;
}
}
module.exports = function (
appPath,
appName,
verbose,
originalDirectory,
templateName
) {
const appPackage = require(path.join(appPath, 'package.json'));
const useYarn = fs.existsSync(path.join(appPath, 'yarn.lock'));
if (!templateName) {
console.log('');
console.error(
`A template was not provided. This is likely because you're using an outdated version of ${chalk.cyan(
'create-react-app'
)}.`
);
console.error(
`Please note that global installs of ${chalk.cyan(
'create-react-app'
)} are no longer supported.`
);
console.error(
`You can fix this by running ${chalk.cyan(
'npm uninstall -g create-react-app'
)} or ${chalk.cyan(
'yarn global remove create-react-app'
)} before using ${chalk.cyan('create-react-app')} again.`
);
return;
}
const templatePath = path.dirname(
require.resolve(`${templateName}/package.json`, { paths: [appPath] })
);
const templateJsonPath = path.join(templatePath, 'template.json');
let templateJson = {};
if (fs.existsSync(templateJsonPath)) {
templateJson = require(templateJsonPath);
}
const templatePackage = templateJson.package || {};
// This was deprecated in CRA v5.
if (templateJson.dependencies || templateJson.scripts) {
console.log();
console.log(
chalk.red(
'Root-level `dependencies` and `scripts` keys in `template.json` were deprecated for Create React App 5.\n' +
'This template needs to be updated to use the new `package` key.'
)
);
console.log('For more information, visit https://cra.link/templates');
}
// Keys to ignore in templatePackage
const templatePackageBlacklist = [
'name',
'version',
'description',
'keywords',
'bugs',
'license',
'author',
'contributors',
'files',
'browser',
'bin',
'man',
'directories',
'repository',
'peerDependencies',
'bundledDependencies',
'optionalDependencies',
'engineStrict',
'os',
'cpu',
'preferGlobal',
'private',
'publishConfig',
];
// Keys from templatePackage that will be merged with appPackage
const templatePackageToMerge = ['dependencies', 'scripts'];
// Keys from templatePackage that will be added to appPackage,
// replacing any existing entries.
const templatePackageToReplace = Object.keys(templatePackage).filter(key => {
return (
!templatePackageBlacklist.includes(key) &&
!templatePackageToMerge.includes(key)
);
});
// Copy over some of the devDependencies
appPackage.dependencies = appPackage.dependencies || {};
// Setup the script rules
const templateScripts = templatePackage.scripts || {};
appPackage.scripts = Object.assign(
{
start: 'react-scripts start',
build: 'react-scripts build',
test: 'react-scripts test',
eject: 'react-scripts eject',
},
templateScripts
);
// Update scripts for Yarn users
if (useYarn) {
appPackage.scripts = Object.entries(appPackage.scripts).reduce(
(acc, [key, value]) => ({
...acc,
[key]: value.replace(/(npm run |npm )/, 'yarn '),
}),
{}
);
}
// Setup the eslint config
appPackage.eslintConfig = {
extends: 'react-app',
};
// Setup the browsers list
appPackage.browserslist = defaultBrowsers;
// Add templatePackage keys/values to appPackage, replacing existing entries
templatePackageToReplace.forEach(key => {
appPackage[key] = templatePackage[key];
});
fs.writeFileSync(
path.join(appPath, 'package.json'),
JSON.stringify(appPackage, null, 2) + os.EOL
);
const readmeExists = fs.existsSync(path.join(appPath, 'README.md'));
if (readmeExists) {
fs.renameSync(
path.join(appPath, 'README.md'),
path.join(appPath, 'README.old.md')
);
}
// Copy the files for the user
const templateDir = path.join(templatePath, 'template');
if (fs.existsSync(templateDir)) {
fs.copySync(templateDir, appPath);
} else {
console.error(
`Could not locate supplied template: ${chalk.green(templateDir)}`
);
return;
}
// modifies README.md commands based on user used package manager.
if (useYarn) {
try {
const readme = fs.readFileSync(path.join(appPath, 'README.md'), 'utf8');
fs.writeFileSync(
path.join(appPath, 'README.md'),
readme.replace(/(npm run |npm )/g, 'yarn '),
'utf8'
);
} catch (err) {
// Silencing the error. As it fall backs to using default npm commands.
}
}
const gitignoreExists = fs.existsSync(path.join(appPath, '.gitignore'));
if (gitignoreExists) {
// Append if there's already a `.gitignore` file there
const data = fs.readFileSync(path.join(appPath, 'gitignore'));
fs.appendFileSync(path.join(appPath, '.gitignore'), data);
fs.unlinkSync(path.join(appPath, 'gitignore'));
} else {
// Rename gitignore after the fact to prevent npm from renaming it to .npmignore
// See: https://github.com/npm/npm/issues/1862
fs.moveSync(
path.join(appPath, 'gitignore'),
path.join(appPath, '.gitignore'),
[]
);
}
// Initialize git repo
let initializedGit = false;
if (tryGitInit()) {
initializedGit = true;
console.log();
console.log('Initialized a git repository.');
}
let command;
let remove;
let args;
if (useYarn) {
command = 'yarnpkg';
remove = 'remove';
args = ['add'];
} else {
command = 'npm';
remove = 'uninstall';
args = [
'install',
'--no-audit', // https://github.com/facebook/create-react-app/issues/11174
'--save',
verbose && '--verbose',
].filter(e => e);
}
// Install additional template dependencies, if present.
const dependenciesToInstall = Object.entries({
...templatePackage.dependencies,
...templatePackage.devDependencies,
});
if (dependenciesToInstall.length) {
args = args.concat(
dependenciesToInstall.map(([dependency, version]) => {
return `${dependency}@${version}`;
})
);
}
// Install react and react-dom for backward compatibility with old CRA cli
// which doesn't install react and react-dom along with react-scripts
if (!isReactInstalled(appPackage)) {
args = args.concat(['react', 'react-dom']);
}
// Install template dependencies, and react and react-dom if missing.
if ((!isReactInstalled(appPackage) || templateName) && args.length > 1) {
console.log();
console.log(`Installing template dependencies using ${command}...`);
const proc = spawn.sync(command, args, { stdio: 'inherit' });
if (proc.status !== 0) {
console.error(`\`${command} ${args.join(' ')}\` failed`);
return;
}
}
if (args.find(arg => arg.includes('typescript'))) {
console.log();
verifyTypeScriptSetup();
}
// Remove template
console.log(`Removing template package using ${command}...`);
console.log();
const proc = spawn.sync(command, [remove, templateName], {
stdio: 'inherit',
});
if (proc.status !== 0) {
console.error(`\`${command} ${args.join(' ')}\` failed`);
return;
}
// Create git commit if git repo was initialized
if (initializedGit && tryGitCommit(appPath)) {
console.log();
console.log('Created git commit.');
}
// Display the most elegant way to cd.
// This needs to handle an undefined originalDirectory for
// backward compatibility with old global-cli's.
let cdpath;
if (originalDirectory && path.join(originalDirectory, appName) === appPath) {
cdpath = appName;
} else {
cdpath = appPath;
}
// Change displayed command to yarn instead of yarnpkg
const displayedCommand = useYarn ? 'yarn' : 'npm';
console.log();
console.log(`Success! Created ${appName} at ${appPath}`);
console.log('Inside that directory, you can run several commands:');
console.log();
console.log(chalk.cyan(` ${displayedCommand} start`));
console.log(' Starts the development server.');
console.log();
console.log(
chalk.cyan(` ${displayedCommand} ${useYarn ? '' : 'run '}build`)
);
console.log(' Bundles the app into static files for production.');
console.log();
console.log(chalk.cyan(` ${displayedCommand} test`));
console.log(' Starts the test runner.');
console.log();
console.log(
chalk.cyan(` ${displayedCommand} ${useYarn ? '' : 'run '}eject`)
);
console.log(
' Removes this tool and copies build dependencies, configuration files'
);
console.log(
' and scripts into the app directory. If you do this, you can’t go back!'
);
console.log();
console.log('We suggest that you begin by typing:');
console.log();
console.log(chalk.cyan(' cd'), cdpath);
console.log(` ${chalk.cyan(`${displayedCommand} start`)}`);
if (readmeExists) {
console.log();
console.log(
chalk.yellow(
'You had a `README.md` file, we renamed it to `README.old.md`'
)
);
}
console.log();
console.log('Happy hacking!');
};
function isReactInstalled(appPackage) {
const dependencies = appPackage.dependencies || {};
return (
typeof dependencies.react !== 'undefined' &&
typeof dependencies['react-dom'] !== 'undefined'
);
}
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-scripts/scripts/utils/createJestConfig.js | packages/react-scripts/scripts/utils/createJestConfig.js | // @remove-file-on-eject
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
const fs = require('fs');
const chalk = require('react-dev-utils/chalk');
const paths = require('../../config/paths');
const modules = require('../../config/modules');
module.exports = (resolve, rootDir, isEjecting) => {
// Use this instead of `paths.testsSetup` to avoid putting
// an absolute filename into configuration after ejecting.
const setupTestsMatches = paths.testsSetup.match(/src[/\\]setupTests\.(.+)/);
const setupTestsFileExtension =
(setupTestsMatches && setupTestsMatches[1]) || 'js';
const setupTestsFile = fs.existsSync(paths.testsSetup)
? `<rootDir>/src/setupTests.${setupTestsFileExtension}`
: undefined;
const config = {
roots: ['<rootDir>/src'],
collectCoverageFrom: ['src/**/*.{js,jsx,ts,tsx}', '!src/**/*.d.ts'],
setupFiles: [
isEjecting
? 'react-app-polyfill/jsdom'
: require.resolve('react-app-polyfill/jsdom'),
],
setupFilesAfterEnv: setupTestsFile ? [setupTestsFile] : [],
testMatch: [
'<rootDir>/src/**/__tests__/**/*.{js,jsx,ts,tsx}',
'<rootDir>/src/**/*.{spec,test}.{js,jsx,ts,tsx}',
],
testEnvironment: 'jsdom',
transform: {
'^.+\\.(js|jsx|mjs|cjs|ts|tsx)$': resolve(
'config/jest/babelTransform.js'
),
'^.+\\.css$': resolve('config/jest/cssTransform.js'),
'^(?!.*\\.(js|jsx|mjs|cjs|ts|tsx|css|json)$)': resolve(
'config/jest/fileTransform.js'
),
},
transformIgnorePatterns: [
'[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs|cjs|ts|tsx)$',
'^.+\\.module\\.(css|sass|scss)$',
],
modulePaths: modules.additionalModulePaths || [],
moduleNameMapper: {
'^react-native$': 'react-native-web',
'^.+\\.module\\.(css|sass|scss)$': 'identity-obj-proxy',
...(modules.jestAliases || {}),
},
moduleFileExtensions: [...paths.moduleFileExtensions, 'node'].filter(
ext => !ext.includes('mjs')
),
watchPlugins: [
'jest-watch-typeahead/filename',
'jest-watch-typeahead/testname',
],
resetMocks: true,
};
if (rootDir) {
config.rootDir = rootDir;
}
const overrides = Object.assign({}, require(paths.appPackageJson).jest);
const supportedKeys = [
'clearMocks',
'collectCoverageFrom',
'coveragePathIgnorePatterns',
'coverageReporters',
'coverageThreshold',
'displayName',
'extraGlobals',
'globalSetup',
'globalTeardown',
'moduleNameMapper',
'resetMocks',
'resetModules',
'restoreMocks',
'snapshotSerializers',
'testMatch',
'transform',
'transformIgnorePatterns',
'watchPathIgnorePatterns',
];
if (overrides) {
supportedKeys.forEach(key => {
if (Object.prototype.hasOwnProperty.call(overrides, key)) {
if (Array.isArray(config[key]) || typeof config[key] !== 'object') {
// for arrays or primitive types, directly override the config key
config[key] = overrides[key];
} else {
// for object types, extend gracefully
config[key] = Object.assign({}, config[key], overrides[key]);
}
delete overrides[key];
}
});
const unsupportedKeys = Object.keys(overrides);
if (unsupportedKeys.length) {
const isOverridingSetupFile =
unsupportedKeys.indexOf('setupFilesAfterEnv') > -1;
if (isOverridingSetupFile) {
console.error(
chalk.red(
'We detected ' +
chalk.bold('setupFilesAfterEnv') +
' in your package.json.\n\n' +
'Remove it from Jest configuration, and put the initialization code in ' +
chalk.bold('src/setupTests.js') +
'.\nThis file will be loaded automatically.\n'
)
);
} else {
console.error(
chalk.red(
'\nOut of the box, Create React App only supports overriding ' +
'these Jest options:\n\n' +
supportedKeys
.map(key => chalk.bold(' \u2022 ' + key))
.join('\n') +
'.\n\n' +
'These options in your package.json Jest configuration ' +
'are not currently supported by Create React App:\n\n' +
unsupportedKeys
.map(key => chalk.bold(' \u2022 ' + key))
.join('\n') +
'\n\nIf you wish to override other Jest options, you need to ' +
'eject from the default setup. You can do so by running ' +
chalk.bold('npm run eject') +
' but remember that this is a one-way operation. ' +
'You may also file an issue with Create React App to discuss ' +
'supporting more options out of the box.\n'
)
);
}
process.exit(1);
}
}
return config;
};
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-scripts/scripts/utils/verifyTypeScriptSetup.js | packages/react-scripts/scripts/utils/verifyTypeScriptSetup.js | // @remove-file-on-eject
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
const chalk = require('react-dev-utils/chalk');
const fs = require('fs');
const resolve = require('resolve');
const path = require('path');
const paths = require('../../config/paths');
const os = require('os');
const semver = require('semver');
const immer = require('react-dev-utils/immer').produce;
const globby = require('react-dev-utils/globby').sync;
const hasJsxRuntime = (() => {
if (process.env.DISABLE_NEW_JSX_TRANSFORM === 'true') {
return false;
}
try {
require.resolve('react/jsx-runtime', { paths: [paths.appPath] });
return true;
} catch (e) {
return false;
}
})();
function writeJson(fileName, object) {
fs.writeFileSync(
fileName,
JSON.stringify(object, null, 2).replace(/\n/g, os.EOL) + os.EOL
);
}
function verifyNoTypeScript() {
const typescriptFiles = globby(
['**/*.(ts|tsx)', '!**/node_modules', '!**/*.d.ts'],
{ cwd: paths.appSrc }
);
if (typescriptFiles.length > 0) {
console.warn(
chalk.yellow(
`We detected TypeScript in your project (${chalk.bold(
`src${path.sep}${typescriptFiles[0]}`
)}) and created a ${chalk.bold('tsconfig.json')} file for you.`
)
);
console.warn();
return false;
}
return true;
}
function verifyTypeScriptSetup() {
let firstTimeSetup = false;
if (!fs.existsSync(paths.appTsConfig)) {
if (verifyNoTypeScript()) {
return;
}
writeJson(paths.appTsConfig, {});
firstTimeSetup = true;
}
const isYarn = fs.existsSync(paths.yarnLockFile);
// Ensure typescript is installed
let ts;
try {
// TODO: Remove this hack once `globalThis` issue is resolved
// https://github.com/jsdom/jsdom/issues/2961
const globalThisWasDefined = !!global.globalThis;
ts = require(resolve.sync('typescript', {
basedir: paths.appNodeModules,
}));
if (!globalThisWasDefined && !!global.globalThis) {
delete global.globalThis;
}
} catch (_) {
console.error(
chalk.bold.red(
`It looks like you're trying to use TypeScript but do not have ${chalk.bold(
'typescript'
)} installed.`
)
);
console.error(
chalk.bold(
'Please install',
chalk.cyan.bold('typescript'),
'by running',
chalk.cyan.bold(
isYarn ? 'yarn add typescript' : 'npm install typescript'
) + '.'
)
);
console.error(
chalk.bold(
'If you are not trying to use TypeScript, please remove the ' +
chalk.cyan('tsconfig.json') +
' file from your package root (and any TypeScript files).'
)
);
console.error();
process.exit(1);
}
const compilerOptions = {
// These are suggested values and will be set when not present in the
// tsconfig.json
// 'parsedValue' matches the output value from ts.parseJsonConfigFileContent()
target: {
parsedValue: ts.ScriptTarget.ES5,
suggested: 'es5',
},
lib: { suggested: ['dom', 'dom.iterable', 'esnext'] },
allowJs: { suggested: true },
skipLibCheck: { suggested: true },
esModuleInterop: { suggested: true },
allowSyntheticDefaultImports: { suggested: true },
strict: { suggested: true },
forceConsistentCasingInFileNames: { suggested: true },
noFallthroughCasesInSwitch: { suggested: true },
// These values are required and cannot be changed by the user
// Keep this in sync with the webpack config
module: {
parsedValue: ts.ModuleKind.ESNext,
value: 'esnext',
reason: 'for import() and import/export',
},
moduleResolution: {
parsedValue: ts.ModuleResolutionKind.NodeJs,
value: 'node',
reason: 'to match webpack resolution',
},
resolveJsonModule: { value: true, reason: 'to match webpack loader' },
isolatedModules: { value: true, reason: 'implementation limitation' },
noEmit: { value: true },
jsx: {
parsedValue:
hasJsxRuntime && semver.gte(ts.version, '4.1.0-beta')
? ts.JsxEmit.ReactJSX
: ts.JsxEmit.React,
value:
hasJsxRuntime && semver.gte(ts.version, '4.1.0-beta')
? 'react-jsx'
: 'react',
reason: 'to support the new JSX transform in React 17',
},
paths: { value: undefined, reason: 'aliased imports are not supported' },
};
const formatDiagnosticHost = {
getCanonicalFileName: fileName => fileName,
getCurrentDirectory: ts.sys.getCurrentDirectory,
getNewLine: () => os.EOL,
};
const messages = [];
let appTsConfig;
let parsedTsConfig;
let parsedCompilerOptions;
try {
const { config: readTsConfig, error } = ts.readConfigFile(
paths.appTsConfig,
ts.sys.readFile
);
if (error) {
throw new Error(ts.formatDiagnostic(error, formatDiagnosticHost));
}
appTsConfig = readTsConfig;
// Get TS to parse and resolve any "extends"
// Calling this function also mutates the tsconfig above,
// adding in "include" and "exclude", but the compilerOptions remain untouched
let result;
parsedTsConfig = immer(readTsConfig, config => {
result = ts.parseJsonConfigFileContent(
config,
ts.sys,
path.dirname(paths.appTsConfig)
);
});
if (result.errors && result.errors.length) {
throw new Error(
ts.formatDiagnostic(result.errors[0], formatDiagnosticHost)
);
}
parsedCompilerOptions = result.options;
} catch (e) {
if (e && e.name === 'SyntaxError') {
console.error(
chalk.red.bold(
'Could not parse',
chalk.cyan('tsconfig.json') + '.',
'Please make sure it contains syntactically correct JSON.'
)
);
}
console.log(e && e.message ? `${e.message}` : '');
process.exit(1);
}
if (appTsConfig.compilerOptions == null) {
appTsConfig.compilerOptions = {};
firstTimeSetup = true;
}
for (const option of Object.keys(compilerOptions)) {
const { parsedValue, value, suggested, reason } = compilerOptions[option];
const valueToCheck = parsedValue === undefined ? value : parsedValue;
const coloredOption = chalk.cyan('compilerOptions.' + option);
if (suggested != null) {
if (parsedCompilerOptions[option] === undefined) {
appTsConfig = immer(appTsConfig, config => {
config.compilerOptions[option] = suggested;
});
messages.push(
`${coloredOption} to be ${chalk.bold(
'suggested'
)} value: ${chalk.cyan.bold(suggested)} (this can be changed)`
);
}
} else if (parsedCompilerOptions[option] !== valueToCheck) {
appTsConfig = immer(appTsConfig, config => {
config.compilerOptions[option] = value;
});
messages.push(
`${coloredOption} ${chalk.bold(
valueToCheck == null ? 'must not' : 'must'
)} be ${valueToCheck == null ? 'set' : chalk.cyan.bold(value)}` +
(reason != null ? ` (${reason})` : '')
);
}
}
// tsconfig will have the merged "include" and "exclude" by this point
if (parsedTsConfig.include == null) {
appTsConfig = immer(appTsConfig, config => {
config.include = ['src'];
});
messages.push(
`${chalk.cyan('include')} should be ${chalk.cyan.bold('src')}`
);
}
if (messages.length > 0) {
if (firstTimeSetup) {
console.log(
chalk.bold(
'Your',
chalk.cyan('tsconfig.json'),
'has been populated with default values.'
)
);
console.log();
} else {
console.warn(
chalk.bold(
'The following changes are being made to your',
chalk.cyan('tsconfig.json'),
'file:'
)
);
messages.forEach(message => {
console.warn(' - ' + message);
});
console.warn();
}
writeJson(paths.appTsConfig, appTsConfig);
}
// Reference `react-scripts` types
if (!fs.existsSync(paths.appTypeDeclarations)) {
fs.writeFileSync(
paths.appTypeDeclarations,
`/// <reference types="react-scripts" />${os.EOL}`
);
}
}
module.exports = verifyTypeScriptSetup;
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-scripts/fixtures/kitchensink/template/jest.integration.config.js | packages/react-scripts/fixtures/kitchensink/template/jest.integration.config.js | 'use strict';
module.exports = {
testEnvironment: 'node',
testMatch: ['**/integration/*.test.js'],
transform: { '^.+\\.js$': './jest.transform.js' },
};
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-scripts/fixtures/kitchensink/template/jest.transform.js | packages/react-scripts/fixtures/kitchensink/template/jest.transform.js | 'use strict';
const babelOptions = { presets: ['react-app'] };
const babelJest = require('babel-jest').default;
module.exports = babelJest.createTransformer(babelOptions);
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-scripts/fixtures/kitchensink/template/integration/webpack.test.js | packages/react-scripts/fixtures/kitchensink/template/integration/webpack.test.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import initDOM, { fetchFile } from './initDOM';
import url from 'url';
const matchCSS = (doc, regexes) => {
if (process.env.E2E_FILE) {
const elements = doc.getElementsByTagName('link');
let href = '';
for (const elem of elements) {
if (elem.rel === 'stylesheet') {
href = elem.href;
}
}
const textContent = fetchFile(url.parse(href));
for (const regex of regexes) {
expect(textContent).toMatch(regex);
}
} else {
for (let i = 0; i < regexes.length; ++i) {
expect(
doc.getElementsByTagName('style')[i].textContent.replace(/\s/g, '')
).toMatch(regexes[i]);
}
}
};
describe('Integration', () => {
describe('webpack plugins', () => {
let doc;
afterEach(() => {
doc && doc.defaultView.close();
doc = undefined;
});
it('css inclusion', async () => {
doc = await initDOM('css-inclusion');
matchCSS(doc, [
/html\{/,
/#feature-css-inclusion\{background:.+;color:.+}/,
]);
});
it('css modules inclusion', async () => {
doc = await initDOM('css-modules-inclusion');
matchCSS(doc, [
/.+style_cssModulesInclusion__.+\{background:.+;color:.+}/,
/.+assets_cssModulesIndexInclusion__.+\{background:.+;color:.+}/,
]);
});
it('scss inclusion', async () => {
doc = await initDOM('scss-inclusion');
matchCSS(doc, [/#feature-scss-inclusion\{background:.+;color:.+}/]);
});
it('scss modules inclusion', async () => {
doc = await initDOM('scss-modules-inclusion');
matchCSS(doc, [
/.+scss-styles_scssModulesInclusion.+\{background:.+;color:.+}/,
/.+assets_scssModulesIndexInclusion.+\{background:.+;color:.+}/,
]);
});
it('sass inclusion', async () => {
doc = await initDOM('sass-inclusion');
matchCSS(doc, [/#feature-sass-inclusion\{background:.+;color:.+}/]);
});
it('sass modules inclusion', async () => {
doc = await initDOM('sass-modules-inclusion');
matchCSS(doc, [
/.+sass-styles_sassModulesInclusion.+\{background:.+;color:.+}/,
/.+assets_sassModulesIndexInclusion.+\{background:.+;color:.+}/,
]);
});
it('image inclusion', async () => {
doc = await initDOM('image-inclusion');
expect(doc.getElementById('feature-image-inclusion').src).toMatch(
/^data:image\/jpeg;base64.+=$/
);
});
it('no ext inclusion', async () => {
doc = await initDOM('no-ext-inclusion');
// Webpack 4 added a default extension ".bin" seems like webpack 5 asset modules do not
expect(
doc.getElementById('feature-no-ext-inclusion').getAttribute('href')
).toMatch(/\/static\/media\/aFileWithoutExt\.[a-f0-9]+$/);
});
it('json inclusion', async () => {
doc = await initDOM('json-inclusion');
expect(doc.getElementById('feature-json-inclusion').textContent).toBe(
'This is an abstract.'
);
});
it('linked modules', async () => {
doc = await initDOM('linked-modules');
expect(doc.getElementById('feature-linked-modules').textContent).toBe(
'2.0.0'
);
});
it('svg inclusion', async () => {
doc = await initDOM('svg-inclusion');
expect(doc.getElementById('feature-svg-inclusion').src).toMatch(
/\/static\/media\/logo\..+\.svg$/
);
});
it('svg component', async () => {
doc = await initDOM('svg-component');
expect(doc.getElementById('feature-svg-component').textContent).toBe('');
});
it('svg in css', async () => {
doc = await initDOM('svg-in-css');
matchCSS(doc, [/\/static\/media\/logo\..+\.svg/]);
});
it('unknown ext inclusion', async () => {
doc = await initDOM('unknown-ext-inclusion');
expect(
doc.getElementById('feature-unknown-ext-inclusion').getAttribute('href')
).toMatch(/\/static\/media\/aFileWithExt\.[a-f0-9]+\.unknown$/);
});
});
});
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-scripts/fixtures/kitchensink/template/integration/syntax.test.js | packages/react-scripts/fixtures/kitchensink/template/integration/syntax.test.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import initDOM from './initDOM';
describe('Integration', () => {
describe('Language syntax', () => {
let doc;
afterEach(() => {
doc && doc.defaultView.close();
doc = undefined;
});
it('array destructuring', async () => {
doc = await initDOM('array-destructuring');
expect(
doc.getElementById('feature-array-destructuring').childElementCount
).toBe(4);
});
it('array spread', async () => {
doc = await initDOM('array-spread');
expect(doc.getElementById('feature-array-spread').childElementCount).toBe(
4
);
});
it('async/await', async () => {
doc = await initDOM('async-await');
expect(doc.getElementById('feature-async-await').childElementCount).toBe(
4
);
});
it('class properties', async () => {
doc = await initDOM('class-properties');
expect(
doc.getElementById('feature-class-properties').childElementCount
).toBe(4);
});
it('computed properties', async () => {
doc = await initDOM('computed-properties');
expect(
doc.getElementById('feature-computed-properties').childElementCount
).toBe(4);
});
it('custom interpolation', async () => {
doc = await initDOM('custom-interpolation');
expect(
doc.getElementById('feature-custom-interpolation').childElementCount
).toBe(4);
});
it('default parameters', async () => {
doc = await initDOM('default-parameters');
expect(
doc.getElementById('feature-default-parameters').childElementCount
).toBe(4);
});
it('destructuring and await', async () => {
doc = await initDOM('destructuring-and-await');
expect(
doc.getElementById('feature-destructuring-and-await').childElementCount
).toBe(4);
});
it('generators', async () => {
doc = await initDOM('generators');
expect(doc.getElementById('feature-generators').childElementCount).toBe(
4
);
});
it('object destructuring', async () => {
doc = await initDOM('object-destructuring');
expect(
doc.getElementById('feature-object-destructuring').childElementCount
).toBe(4);
});
it('object spread', async () => {
doc = await initDOM('object-spread');
expect(
doc.getElementById('feature-object-spread').childElementCount
).toBe(4);
});
it('promises', async () => {
doc = await initDOM('promises');
expect(doc.getElementById('feature-promises').childElementCount).toBe(4);
});
it('rest + default', async () => {
doc = await initDOM('rest-and-default');
expect(
doc.getElementById('feature-rest-and-default').childElementCount
).toBe(4);
});
it('rest parameters', async () => {
doc = await initDOM('rest-parameters');
expect(
doc.getElementById('feature-rest-parameters').childElementCount
).toBe(4);
});
it('template interpolation', async () => {
doc = await initDOM('template-interpolation');
expect(
doc.getElementById('feature-template-interpolation').childElementCount
).toBe(4);
});
});
});
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-scripts/fixtures/kitchensink/template/integration/env.test.js | packages/react-scripts/fixtures/kitchensink/template/integration/env.test.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import initDOM from './initDOM';
describe('Integration', () => {
describe('Environment variables', () => {
let doc;
afterEach(() => {
doc && doc.defaultView.close();
doc = undefined;
});
it('file env variables', async () => {
doc = await initDOM('file-env-variables');
expect(
doc.getElementById('feature-file-env-original-1').textContent
).toBe('from-original-env-1');
expect(
doc.getElementById('feature-file-env-original-2').textContent
).toBe('override-from-original-local-env-2');
expect(doc.getElementById('feature-file-env').textContent).toBe(
process.env.NODE_ENV === 'production' ? 'production' : 'development'
);
expect(doc.getElementById('feature-file-env-x').textContent).toBe(
'x-from-original-local-env'
);
});
it('PUBLIC_URL', async () => {
doc = await initDOM('public-url');
const prefix =
process.env.NODE_ENV === 'development'
? ''
: 'http://www.example.org/spa';
expect(doc.getElementById('feature-public-url').textContent).toBe(
`${prefix}.`
);
expect(
doc.querySelector('head link[rel="icon"]').getAttribute('href')
).toBe(`${prefix}/favicon.ico`);
});
it('shell env variables', async () => {
doc = await initDOM('shell-env-variables');
expect(
doc.getElementById('feature-shell-env-variables').textContent
).toBe('fromtheshell.');
});
it('expand .env variables', async () => {
doc = await initDOM('expand-env-variables');
expect(doc.getElementById('feature-expand-env-1').textContent).toBe(
'basic'
);
expect(doc.getElementById('feature-expand-env-2').textContent).toBe(
'basic'
);
expect(doc.getElementById('feature-expand-env-3').textContent).toBe(
'basic'
);
expect(
doc.getElementById('feature-expand-env-existing').textContent
).toBe('fromtheshell');
});
});
});
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-scripts/fixtures/kitchensink/template/integration/config.test.js | packages/react-scripts/fixtures/kitchensink/template/integration/config.test.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import initDOM from './initDOM';
describe('Integration', () => {
describe('jsconfig.json/tsconfig.json', () => {
let doc;
afterEach(() => {
doc && doc.defaultView.close();
doc = undefined;
});
it('Supports setting baseUrl to src', async () => {
doc = await initDOM('base-url');
expect(doc.getElementById('feature-base-url').childElementCount).toBe(4);
});
});
});
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-scripts/fixtures/kitchensink/template/integration/initDOM.js | packages/react-scripts/fixtures/kitchensink/template/integration/initDOM.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const fs = require('fs');
const { JSDOM, ResourceLoader } = require('jsdom');
const path = require('path');
const url = require('url');
const file =
process.env.E2E_FILE &&
(path.isAbsolute(process.env.E2E_FILE)
? process.env.E2E_FILE
: path.join(process.cwd(), process.env.E2E_FILE));
export const fetchFile = url => {
const pathPrefix = process.env.PUBLIC_URL.replace(/^https?:\/\/[^/]+\/?/, '');
return fs.readFileSync(
path.join(path.dirname(file), url.pathname.replace(pathPrefix, '')),
'utf8'
);
};
const fileResourceLoader =
new (class FileResourceLoader extends ResourceLoader {
fetch(href, options) {
return Promise.resolve(fetchFile(url.parse(href)));
}
})();
if (!process.env.E2E_FILE && !process.env.E2E_URL) {
it.only('can run jsdom (at least one of "E2E_FILE" or "E2E_URL" environment variables must be provided)', () => {
expect(
new Error("This isn't the error you are looking for.")
).toBeUndefined();
});
}
const initDOM = async feature =>
// eslint-disable-next-line no-async-promise-executor
new Promise(async (resolve, reject) => {
try {
const host = process.env.E2E_URL || 'http://www.example.org/spa:3000';
const url = `${host}#${feature}`;
let window;
if (process.env.E2E_FILE) {
window = (
await JSDOM.fromFile(file, {
pretendToBeVisual: true,
resources: fileResourceLoader,
runScripts: 'dangerously',
url,
})
).window;
} else {
window = (
await JSDOM.fromURL(url, {
pretendToBeVisual: true,
resources: 'usable',
runScripts: 'dangerously',
})
).window;
}
const cleanup = () => {
if (window) {
window.close();
window = null;
}
};
const { document } = window;
const cancelToken = setTimeout(() => {
// Cleanup jsdom instance since we don't need it anymore
cleanup();
reject(`Timed out loading feature: ${feature}`);
}, 10000);
document.addEventListener(
'ReactFeatureDidMount',
() => resolve(document),
{ capture: true, once: true }
);
document.addEventListener(
'ReactFeatureError',
() => {
clearTimeout(cancelToken);
// Cleanup jsdom instance since we don't need it anymore
cleanup();
reject(`Error loading feature: ${feature}`);
},
{ capture: true, once: true }
);
} catch (e) {
reject(e);
}
});
export default initDOM;
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-scripts/fixtures/kitchensink/template/src/absoluteLoad.js | packages/react-scripts/fixtures/kitchensink/template/src/absoluteLoad.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const absoluteLoad = () => [
{ id: 1, name: '1' },
{ id: 2, name: '2' },
{ id: 3, name: '3' },
{ id: 4, name: '4' },
];
export default absoluteLoad;
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-scripts/fixtures/kitchensink/template/src/index.js | packages/react-scripts/fixtures/kitchensink/template/src/index.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import App from './App';
import ReactDOMClient from 'react-dom/client';
ReactDOMClient.createRoot(document.getElementById('root')).render(<App />);
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-scripts/fixtures/kitchensink/template/src/App.js | packages/react-scripts/fixtures/kitchensink/template/src/App.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React, { Component, createElement } from 'react';
import PropTypes from 'prop-types';
class BuiltEmitter extends Component {
static propTypes = {
error: PropTypes.string,
feature: PropTypes.func,
};
componentDidMount() {
const { error, feature } = this.props;
if (error) {
this.handleError(error);
return;
}
// Class components must call this.props.onReady when they're ready for the test.
// We will assume functional components are ready immediately after mounting.
if (!Object.prototype.isPrototypeOf.call(Component, feature)) {
this.handleReady();
}
}
handleError(error) {
document.dispatchEvent(new Event('ReactFeatureError'));
}
handleReady() {
document.dispatchEvent(new Event('ReactFeatureDidMount'));
}
render() {
const {
props: { feature },
handleReady,
} = this;
return (
<div>
{feature &&
createElement(feature, {
onReady: handleReady,
})}
</div>
);
}
}
class App extends Component {
constructor(props) {
super(props);
this.state = { feature: null };
this.setFeature = this.setFeature.bind(this);
}
componentDidMount() {
const url = window.location.href;
// const feature = window.location.hash.slice(1);
// This works around an issue of a duplicate hash in the href
// Ex: http://localhost:3001/#array-destructuring#array-destructuring
// This seems like a jsdom bug as the URL in initDom.js appears to be correct
const feature = url.slice(url.lastIndexOf('#') + 1);
switch (feature) {
case 'array-destructuring':
import('./features/syntax/ArrayDestructuring').then(f =>
this.setFeature(f.default)
);
break;
case 'array-spread':
import('./features/syntax/ArraySpread').then(f =>
this.setFeature(f.default)
);
break;
case 'async-await':
import('./features/syntax/AsyncAwait').then(f =>
this.setFeature(f.default)
);
break;
case 'class-properties':
import('./features/syntax/ClassProperties').then(f =>
this.setFeature(f.default)
);
break;
case 'computed-properties':
import('./features/syntax/ComputedProperties').then(f =>
this.setFeature(f.default)
);
break;
case 'css-inclusion':
import('./features/webpack/CssInclusion').then(f =>
this.setFeature(f.default)
);
break;
case 'css-modules-inclusion':
import('./features/webpack/CssModulesInclusion').then(f =>
this.setFeature(f.default)
);
break;
case 'scss-inclusion':
import('./features/webpack/ScssInclusion').then(f =>
this.setFeature(f.default)
);
break;
case 'scss-modules-inclusion':
import('./features/webpack/ScssModulesInclusion').then(f =>
this.setFeature(f.default)
);
break;
case 'sass-inclusion':
import('./features/webpack/SassInclusion').then(f =>
this.setFeature(f.default)
);
break;
case 'sass-modules-inclusion':
import('./features/webpack/SassModulesInclusion').then(f =>
this.setFeature(f.default)
);
break;
case 'custom-interpolation':
import('./features/syntax/CustomInterpolation').then(f =>
this.setFeature(f.default)
);
break;
case 'default-parameters':
import('./features/syntax/DefaultParameters').then(f =>
this.setFeature(f.default)
);
break;
case 'destructuring-and-await':
import('./features/syntax/DestructuringAndAwait').then(f =>
this.setFeature(f.default)
);
break;
case 'file-env-variables':
import('./features/env/FileEnvVariables').then(f =>
this.setFeature(f.default)
);
break;
case 'generators':
import('./features/syntax/Generators').then(f =>
this.setFeature(f.default)
);
break;
case 'image-inclusion':
import('./features/webpack/ImageInclusion').then(f =>
this.setFeature(f.default)
);
break;
case 'json-inclusion':
import('./features/webpack/JsonInclusion').then(f =>
this.setFeature(f.default)
);
break;
case 'linked-modules':
import('./features/webpack/LinkedModules').then(f =>
this.setFeature(f.default)
);
break;
case 'no-ext-inclusion':
import('./features/webpack/NoExtInclusion').then(f =>
this.setFeature(f.default)
);
break;
case 'nullish-coalescing':
import('./features/syntax/NullishCoalescing').then(f =>
this.setFeature(f.default)
);
break;
case 'object-destructuring':
import('./features/syntax/ObjectDestructuring').then(f =>
this.setFeature(f.default)
);
break;
case 'object-spread':
import('./features/syntax/ObjectSpread').then(f =>
this.setFeature(f.default)
);
break;
case 'optional-chaining':
import('./features/syntax/OptionalChaining').then(f =>
this.setFeature(f.default)
);
break;
case 'promises':
import('./features/syntax/Promises').then(f =>
this.setFeature(f.default)
);
break;
case 'public-url':
import('./features/env/PublicUrl').then(f =>
this.setFeature(f.default)
);
break;
case 'rest-and-default':
import('./features/syntax/RestAndDefault').then(f =>
this.setFeature(f.default)
);
break;
case 'rest-parameters':
import('./features/syntax/RestParameters').then(f =>
this.setFeature(f.default)
);
break;
case 'shell-env-variables':
import('./features/env/ShellEnvVariables').then(f =>
this.setFeature(f.default)
);
break;
case 'svg-inclusion':
import('./features/webpack/SvgInclusion').then(f =>
this.setFeature(f.default)
);
break;
case 'svg-component':
import('./features/webpack/SvgComponent').then(f =>
this.setFeature(f.default)
);
break;
case 'svg-in-css':
import('./features/webpack/SvgInCss').then(f =>
this.setFeature(f.default)
);
break;
case 'template-interpolation':
import('./features/syntax/TemplateInterpolation').then(f =>
this.setFeature(f.default)
);
break;
case 'unknown-ext-inclusion':
import('./features/webpack/UnknownExtInclusion').then(f =>
this.setFeature(f.default)
);
break;
case 'expand-env-variables':
import('./features/env/ExpandEnvVariables').then(f =>
this.setFeature(f.default)
);
break;
case 'base-url':
import('./features/config/BaseUrl').then(f =>
this.setFeature(f.default)
);
break;
case 'dynamic-import':
import('./features/webpack/DynamicImport').then(f =>
this.setFeature(f.default)
);
break;
default:
this.setState({ error: `Missing feature "${feature}"` });
}
}
setFeature(feature) {
this.setState({ feature });
}
render() {
const { error, feature } = this.state;
if (error || feature) {
return <BuiltEmitter error={error} feature={feature} />;
}
return null;
}
}
export default App;
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-scripts/fixtures/kitchensink/template/src/subfolder/lol.js | packages/react-scripts/fixtures/kitchensink/template/src/subfolder/lol.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
module.exports = function () {
return `haha`;
};
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-scripts/fixtures/kitchensink/template/src/features/env/FileEnvVariables.test.js | packages/react-scripts/fixtures/kitchensink/template/src/features/env/FileEnvVariables.test.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import FileEnvVariables from './FileEnvVariables';
import ReactDOMClient from 'react-dom/client';
import { flushSync } from 'react-dom';
describe('.env variables', () => {
it('renders without crashing', () => {
const div = document.createElement('div');
flushSync(() => {
ReactDOMClient.createRoot(div).render(<FileEnvVariables />);
});
});
});
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-scripts/fixtures/kitchensink/template/src/features/env/PublicUrl.js | packages/react-scripts/fixtures/kitchensink/template/src/features/env/PublicUrl.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
const PublicUrl = () => (
<span id="feature-public-url">{process.env.PUBLIC_URL}.</span>
);
export default PublicUrl;
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-scripts/fixtures/kitchensink/template/src/features/env/ShellEnvVariables.js | packages/react-scripts/fixtures/kitchensink/template/src/features/env/ShellEnvVariables.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
const ShellEnvVariables = () => (
<span id="feature-shell-env-variables">
{process.env.REACT_APP_SHELL_ENV_MESSAGE}.
</span>
);
export default ShellEnvVariables;
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
facebook/create-react-app | https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-scripts/fixtures/kitchensink/template/src/features/env/ExpandEnvVariables.js | packages/react-scripts/fixtures/kitchensink/template/src/features/env/ExpandEnvVariables.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
const ExpandEnvVariables = () => (
<span>
<span id="feature-expand-env-1">{process.env.REACT_APP_BASIC}</span>
<span id="feature-expand-env-2">{process.env.REACT_APP_BASIC_EXPAND}</span>
<span id="feature-expand-env-3">
{process.env.REACT_APP_BASIC_EXPAND_SIMPLE}
</span>
<span id="feature-expand-env-existing">
{process.env.REACT_APP_EXPAND_EXISTING}
</span>
</span>
);
export default ExpandEnvVariables;
| javascript | MIT | 6254386531d263688ccfa542d0e628fbc0de0b28 | 2026-01-04T14:56:49.538607Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.