diff --git a/.eslintignore b/.eslintignore new file mode 100644 index 000000000..4eaf46c6d --- /dev/null +++ b/.eslintignore @@ -0,0 +1,5 @@ +node_modules/ +build +my-app* +packages/react-scripts/template +packages/react-scripts/fixtures diff --git a/.eslintrc b/.eslintrc new file mode 100644 index 000000000..44a504e40 --- /dev/null +++ b/.eslintrc @@ -0,0 +1,17 @@ +{ + "extends": "eslint:recommended", + "env": { + "browser": true, + "commonjs": true, + "node": true, + "es6": true + }, + "parserOptions": { + "ecmaVersion": 6 + }, + "rules": { + "no-console": "off", + "strict": ["error", "global"], + "curly": "warn" + } +} diff --git a/.eslintrc.js b/.eslintrc.js deleted file mode 100644 index 0f8fb0470..000000000 --- a/.eslintrc.js +++ /dev/null @@ -1,7 +0,0 @@ -const clientESLintConfig = require('./config/eslint'); - -module.exports = Object.assign({}, clientESLintConfig, { - env: Object.assign({}, clientESLintConfig.env, { - node: true, - }) -}); diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md new file mode 100644 index 000000000..dc25d841a --- /dev/null +++ b/.github/ISSUE_TEMPLATE.md @@ -0,0 +1,161 @@ + + +### Is this a bug report? + +(write your answer here) + + + + +### Can you also reproduce the problem with npm 4.x? + + + +(Write your answer here.) + + +### Which terms did you search for in User Guide? + + + +(Write your answer here if relevant.) + + +### Environment + + + +1. `npm ls react-scripts-ts` (if you haven’t ejected): +2. `node -v`: +3. `npm -v`: +4. `yarn --version` (if you use Yarn): +5. `npm ls react-scripts-ts` (if you haven’t ejected): + +Then, specify: + +1. Operating system: +2. Browser and version (if relevant): + + +### Steps to Reproduce + + + +(Write your steps here:) + +1. +2. +3. + + +### Expected Behavior + + + +(Write what you thought would happen.) + + +### Actual Behavior + + + +(Write what happened. Please add screenshots!) + + +### Reproducible Demo + + + +(Paste the link to an example project and exact instructions to reproduce the issue.) + + diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 000000000..45268d0b6 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,7 @@ + diff --git a/.gitignore b/.gitignore index f19abba42..b3195405a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,14 @@ +.idea/ +.vscode/ node_modules/ build .DS_Store *.tgz my-app* template/src/__tests__/__snapshots__/ +lerna-debug.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +/.changelog +yarn.lock diff --git a/.travis.yml b/.travis.yml index 3ed709763..7256cff7e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,10 +1,11 @@ --- +dist: trusty language: node_js node_js: - - 4 - - 6 + - 9 cache: directories: - - global-cli/node_modules - node_modules -script: tasks/e2e.sh +install: true +script: + - 'tasks/e2e-simple.sh' diff --git a/.yarnrc b/.yarnrc new file mode 100644 index 000000000..07e44a9a5 --- /dev/null +++ b/.yarnrc @@ -0,0 +1,3 @@ +--install.no-lockfile true +--install.check-files true +--add.no-lockfile true diff --git a/CHANGELOG.md b/CHANGELOG.md deleted file mode 100644 index fb5fea84c..000000000 --- a/CHANGELOG.md +++ /dev/null @@ -1,101 +0,0 @@ -## 0.2.3 (August 25, 2016) - -### Build Dependency (`react-scripts`) - -* You can now [proxy requests to an API server](https://github.com/facebookincubator/create-react-app/blob/ef94b0561d5afb9b50b905fa5cd3f94e965c69c0/template/README.md#proxying-api-requests-in-development) without worrying about CORS. ([@gaearon](https://github.com/gaearon) in [#282](https://github.com/facebookincubator/create-react-app/pull/282)) -* You can now [pass custom environment variables](https://github.com/facebookincubator/create-react-app/blob/ef94b0561d5afb9b50b905fa5cd3f94e965c69c0/template/README.md#adding-custom-environment-variables) to your application. ([@eliperelman](https://github.com/eliperelman) in [#342](https://github.com/facebookincubator/create-react-app/pull/342)) -* You can now [use `async` and `await`](https://ponyfoo.com/articles/understanding-javascript-async-await) syntax. ([@gaearon](https://github.com/gaearon) in [#327](https://github.com/facebookincubator/create-react-app/pull/327), [@fson](https://github.com/fson) in [#332](https://github.com/facebookincubator/create-react-app/pull/332)) -* Paths with period in them now load successfully on the development server. ([@mxstbr](https://github.com/mxstbr) in [#422](https://github.com/facebookincubator/create-react-app/pull/422)) -* Images with `.webp` extension are now supported. ([@gafemoyano](https://github.com/gafemoyano) in [#458](https://github.com/facebookincubator/create-react-app/pull/458)) -* The most recent version of React is now added to `package.json`. ([@wdhorton](https://github.com/wdhorton) in [#477](https://github.com/facebookincubator/create-react-app/pull/477)) -* Babel configuration is simplified. ([@kripod](https://github.com/kripod) in [#490](https://github.com/facebookincubator/create-react-app/pull/490)) - -### Migrating from 0.2.2 to 0.2.3 - -Update `react-scripts` to point to `0.2.3` in your `package.json` and run `npm install`. You shouldn’t need to do anything else. - -Newly created projects will use `0.2.3` automatically. You **don’t** need to update the global `create-react-app` CLI itself. It stays at `0.2.0` for now because it doesn’t have any changes. - -## 0.2.2 (August 22, 2016) - -### Build Dependency (`react-scripts`) - -* When the bundle size changes, we now display the difference after build. ([@elijahmanor](https://github.com/elijahmanor) in [#340](https://github.com/facebookincubator/create-react-app/pull/340)) -* `npm install`ing a missing dependency now forces a rebuild. ([@gaearon](https://github.com/gaearon) in [#349](https://github.com/facebookincubator/create-react-app/pull/349)) -* Autoprefixer config now includes more commonly supported browsers. ([@kripod](https://github.com/kripod) in [#345](https://github.com/facebookincubator/create-react-app/pull/345)) -* All the configuration is now documented inline so ejecting doesn’t leave you in the dark. ([@gaearon](https://github.com/gaearon) in [#362](https://github.com/facebookincubator/create-react-app/pull/362)) -* `Object.assign()` polyfill is now bundled by default. ([@gaearon](https://github.com/gaearon) in [#399](https://github.com/facebookincubator/create-react-app/pull/399)) -* [React Native Web](https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/) now works out of the box. ([@grigio](https://github.com/grigio) in [#407](https://github.com/facebookincubator/create-react-app/pull/407)) -* Same asset filenames in different folders don’t confuse the server now. ([@arunoda](https://github.com/arunoda) in [#446](https://github.com/facebookincubator/create-react-app/pull/446)) -* The `otf` font format is now supported. ([@A-gambit](https://github.com/A-gambit) in [#434](https://github.com/facebookincubator/create-react-app/pull/434)) -* The `new-cap` linting rule has been disabled thanks to feedback from Immutable.js users. ([@rricard](https://github.com/rricard) in [#470](https://github.com/facebookincubator/create-react-app/pull/470)) - -### Migrating from 0.2.1 to 0.2.2 - -Update `react-scripts` to point to `0.2.2` in your `package.json` and run `npm install`. You shouldn’t need to do anything else. - -Newly created projects will use `0.2.2` automatically. You **don’t** need to update the global `create-react-app` CLI itself. It stays at `0.2.0` for now because it doesn’t have any changes. - - -## 0.2.1 (August 1, 2016) - -### Build Dependency (`react-scripts`) - -* Fixes an issue with `npm start` taking a very long time on OS X with Firewall enabled ([@gaearon](https://github.com/gaearon) in [#319](https://github.com/facebookincubator/create-react-app/pull/319)) -* Fixes an issue with Webpack eating a lot of CPU in some cases ([@dceddia](https://github.com/dceddia) in [#294](https://github.com/facebookincubator/create-react-app/pull/294)) -* We now warn if you import a file with mismatched casing because this breaks the watcher ([@alexzherdev](https://github.com/alexzherdev) in [#266](https://github.com/facebookincubator/create-react-app/pull/266)) -* CSS files specifying `?v=` after asset filenames, such as Font Awesome, now works correctly ([@alexzherdev](https://github.com/alexzherdev) in [#298](https://github.com/facebookincubator/create-react-app/pull/298)) -* Issues with `npm link`ing `react-scripts` have been fixed ([@dallonf](https://github.com/dallonf) in [#277](https://github.com/facebookincubator/create-react-app/pull/277)) -* We now use `/static` prefix for assets both in development and production ([@gaearon](https://github.com/gaearon) in [#278](https://github.com/facebookincubator/create-react-app/pull/278)) - -### Migrating from 0.2.0 to 0.2.1 - -Update `react-scripts` to point to `0.2.1` in your `package.json` and run `npm install`. You shouldn’t need to do anything else. If you see a warning about wrong file casing next time you `npm start`, fix your imports to use the correct filename casing. - -Newly created projects will use `0.2.1` automatically. You **don’t** need to update the global `create-react-app` CLI itself. It stays at `0.2.0` for now because it doesn’t have any changes. - -## 0.2.0 (July 28, 2016) - -### Build Dependency (`react-scripts`) - -* You can now enable deployment to GitHub Pages by adding `homepage` field to `package.json` ([@dhruska](https://github.com/dhruska) in [#94](https://github.com/facebookincubator/create-react-app/pull/94)) -* Development server now runs on `0.0.0.0` and works with VirtualBox ([@JWo1F](https://github.com/JWo1F) in [#128](https://github.com/facebookincubator/create-react-app/pull/128)) -* Cloud9 and Nitrous online IDEs are now supported ([@gaearon](http://github.com/gaearon) in [2fe84e](https://github.com/facebookincubator/create-react-app/commit/2fe84ecded55f1d5258d91f9c2c07698ae0d2fb4)) -* When `3000` port is taken, we offer to use another port ([@chocnut](https://github.com/chocnut) in [#101](https://github.com/facebookincubator/create-react-app/pull/101), [2edf21](https://github.com/facebookincubator/create-react-app/commit/2edf2180f2aa6bf647807d0b1fcd95f4cfe4a558)) -* You can now `import` CSS files from npm modules ([@glennreyes](https://github.com/glennreyes) in [#105](https://github.com/facebookincubator/create-react-app/pull/105), [@breaddevil](https://github.com/breaddevil) in [#178](https://github.com/facebookincubator/create-react-app/pull/178)) -* `fetch` and `Promise` polyfills are now always included ([@gaearon](https://github.com/gaearon) in [#235](https://github.com/facebookincubator/create-react-app/pull/235)) -* Regenerator runtime is now included if you use ES6 generators ([@gaearon](https://github.com/gaearon) in [#238](https://github.com/facebookincubator/create-react-app/pull/238)) -* Generated project now contains `.gitignore` ([@npverni](https://github.com/npverni) in [#79](https://github.com/facebookincubator/create-react-app/pull/79), [@chibicode](https://github.com/chibicode) in [#112](https://github.com/facebookincubator/create-react-app/pull/112)) -* ESLint config is now more compatible with Flow ([@gaearon](https://github.com/gaearon) in [#261](https://github.com/facebookincubator/create-react-app/pull/261)) -* A stylistic lint rule about method naming has been removed ([@mxstbr](https://github.com/mxstbr) in [#152](https://github.com/facebookincubator/create-react-app/pull/157)) -* A few unobtrusive accessibility lint rules have been added ([@evcohen](https://github.com/evcohen) in [#175](https://github.com/facebookincubator/create-react-app/pull/175)) -* A `.babelrc` in parent directory no longer causes an error ([@alexzherdev](https://github.com/alexzherdev) in [#236](https://github.com/facebookincubator/create-react-app/pull/236)) -* Files with `.json` extension are now discovered ([@gaearon](https://github.com/gaearon) in [a11d6a](https://github.com/facebookincubator/create-react-app/commit/a11d6a398f487f9163880dd34667b1d3e14b147a)) -* Bug fixes from transitive dependencies are included ([#126](https://github.com/facebookincubator/create-react-app/issues/126)) -* Linting now works with IDEs if you follow [these](https://github.com/facebookincubator/create-react-app/blob/master/template/README.md#display-lint-output-in-the-editor) instructions ([@keyanzhang](https://github.com/keyanzhang) in [#149](https://github.com/facebookincubator/create-react-app/pull/149)) -* After building, we now print gzipped bundle size ([@lvwrence](https://github.com/lvwrence) in [#229](https://github.com/facebookincubator/create-react-app/pull/229)) - -### Global CLI (`create-react-app`) - -* It enforces that you have Node >= 4 ([@conorhastings](https://github.com/conorhastings) in [#88](https://github.com/facebookincubator/create-react-app/pull/88)) -* It handles `--version` flag correctly ([@mxstbr](https://github.com/mxstbr) in [#152](https://github.com/facebookincubator/create-react-app/pull/152)) - -### Migrating from 0.1.0 to 0.2.0 - -You may optionally update the global command (it’s not required): - -``` -npm install -g create-react-app@0.2.0 -``` - -Inside any created project that has not been ejected, run: - -``` -npm install --save-dev --save-exact react-scripts@0.2.0 -``` - -You may need to fix a few lint warnings about missing `` tag, but everything else should work out of the box. If you intend to deploy your site to GitHub Pages, you may now [add `homepage` field to `package.json`](https://github.com/facebookincubator/create-react-app/blob/master/template/README.md#deploy-to-github-pages). If you had [issues with integrating editor linter plugins](https://github.com/facebookincubator/create-react-app/issues/124), follow [these new instructions](https://github.com/facebookincubator/create-react-app/blob/master/template/README.md#display-lint-output-in-the-editor). - -## 0.1.0 (July 22, 2016) - -* Initial public release diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md deleted file mode 100644 index 74d2eb8e9..000000000 --- a/CONTRIBUTING.md +++ /dev/null @@ -1,42 +0,0 @@ -# Contributing to `create-react-app` - -♥ `create-react-app` and want to get involved? Thanks! There are plenty of ways you can help! - -Please take a moment to review this document in order to make the contribution process easy and effective for everyone involved. - -Following these guidelines helps to communicate that you respect the time of the developers managing and developing this open source project. In return, they should reciprocate that respect in addressing your issue or assessing patches and features. - -## Core ideas - -We do not want any flags or configuration, that would defeat the purpose of this tool. We want to find good defaults and actively find ways to improve the developer experience. - -We try not to make any controversial choices. If the community is split between different tools, we won't just pick the least controversial or most popular, the tool itself should be agnostic between them. - -*These ideas are subject to change at any time* - -## Submitting a Pull Request - -Good pull requests - patches, improvements, new features - are a fantastic help. They should remain focused in scope and avoid containing unrelated commits. - -Please **ask first** if somebody else is already working on this or the core developers think your feature is in-scope for `create-react-app`. Generally always have a related issue with discussions for whatever you are including. - -Please also provide a **test plan**, i.e. specify how you verified what you added works. - -## Setting up a local copy of the repository - -1. Clone the repo with `git clone https://github.com/facebookincubator/create-react-app` - -2. Run `npm install` in the root `create-react-app` folder **and** the `create-react-app/global-cli` folder - -Once it is done, you can modify any file locally and run `npm start` or `npm run build` just like in a generated project. - -If you want to try out the end-to-end flow with the global CLI, you can do this too: - -``` -npm run create-react-app my-app -cd my-app -``` - -and then run `npm start` or `npm run build`. - -*Many thanks to [h5bp](https://github.com/h5bp/html5-boilerplate/blob/master/CONTRIBUTING.md) for the inspiration with this contributing guide* diff --git a/LICENSE b/LICENSE deleted file mode 100644 index a6b451216..000000000 --- a/LICENSE +++ /dev/null @@ -1,30 +0,0 @@ -BSD License - -For create-react-app software - -Copyright (c) 2016-present, Facebook, Inc. All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - - * Neither the name Facebook nor the names of its contributors may be used to - endorse or promote products derived from this software without specific - prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/PATENTS b/PATENTS deleted file mode 100644 index ca1e727b7..000000000 --- a/PATENTS +++ /dev/null @@ -1,33 +0,0 @@ -Additional Grant of Patent Rights Version 2 - -"Software" means the create-react-app software distributed by Facebook, Inc. - -Facebook, Inc. ("Facebook") hereby grants to each recipient of the Software -("you") a perpetual, worldwide, royalty-free, non-exclusive, irrevocable -(subject to the termination provision below) license under any Necessary -Claims, to make, have made, use, sell, offer to sell, import, and otherwise -transfer the Software. For avoidance of doubt, no license is granted under -Facebook’s rights in any patent claims that are infringed by (i) modifications -to the Software made by you or any third party or (ii) the Software in -combination with any software or other technology. - -The license granted hereunder will terminate, automatically and without notice, -if you (or any of your subsidiaries, corporate affiliates or agents) initiate -directly or indirectly, or take a direct financial interest in, any Patent -Assertion: (i) against Facebook or any of its subsidiaries or corporate -affiliates, (ii) against any party if such Patent Assertion arises in whole or -in part from any software, technology, product or service of Facebook or any of -its subsidiaries or corporate affiliates, or (iii) against any party relating -to the Software. Notwithstanding the foregoing, if Facebook or any of its -subsidiaries or corporate affiliates files a lawsuit alleging patent -infringement against you in the first instance, and you respond by filing a -patent infringement counterclaim in that lawsuit against that party that is -unrelated to the Software, the license granted hereunder will not terminate -under section (i) of this paragraph due to such counterclaim. - -A "Necessary Claim" is a claim of a patent owned by Facebook that is -necessarily infringed by the Software standing alone. - -A "Patent Assertion" is any lawsuit or other action alleging direct, indirect, -or contributory infringement or inducement to infringe any patent, including a -cross-claim or counterclaim. diff --git a/README.md b/README.md index 2fa9f43d1..2109a8c48 100644 --- a/README.md +++ b/README.md @@ -1,183 +1,209 @@ -# Create React App +### ⛔ DEPRECATED ⛔ +`create-react-app` now supports typescript natively - [read the guide for adding typescript](https://facebook.github.io/create-react-app/docs/adding-typescript) to existing projects. -Create React apps with no build configuration. +For existing `react-scripts-ts` users who would like to upgrade, [follow this guide](https://vincenttunru.com/migrate-create-react-app-typescript-to-create-react-app/). -* [Getting Started](#getting-started) – How to create a new app. -* [User Guide](https://github.com/facebookincubator/create-react-app/blob/master/template/README.md) – How to develop apps bootstrapped with Create React App. +I have chosen to archive this repository, if you need to contact me, i'm on twitter @willmonk. -## tl;dr +--- -```sh -npm install -g create-react-app - -create-react-app my-app -cd my-app/ -npm start - -``` - -Then open [http://localhost:3000/](http://localhost:3000/) to see your app.
-When you’re ready to deploy to production, create a minified bundle with `npm run build`. - -npm start - -## Getting Started - -### Installation - -Install it once globally: - -```sh -npm install -g create-react-app -``` +# `react-scripts-ts` [![npm version](https://badge.fury.io/js/react-scripts-ts.svg)](https://badge.fury.io/js/react-scripts-ts) [![Build Status](https://travis-ci.org/wmonk/create-react-app-typescript.svg?branch=master)](https://travis-ci.org/wmonk/create-react-app-typescript) -**You’ll need to have Node >= 4 on your machine**. We recommend to use Node >= 6 and npm >= 3 for faster installation speed and better disk usage. You can use [nvm](https://github.com/creationix/nvm#usage) to easily switch Node versions between different projects. +Create React apps (with Typescript) with no build configuration. -**This tool doesn’t assume a Node backend**. The Node installation is only required for the build tools that rely on it locally, such as Webpack and Babel. + * [Getting Started](#tldr) – How to create a new app. + * [User Guide](https://github.com/wmonk/create-react-app-typescript/blob/master/template/README.md) – How to develop apps bootstrapped with react scripts ts. -### Creating an App +_Do you know react and want to try out typescript? Or do you know typescript and want to try out react?_ Get all the benefits from `create-react-app` but you use typescript! 🚀 -To create a new app, run: +## Quick Overview ```sh -create-react-app my-app +npx create-react-app my-app --scripts-version=react-scripts-ts cd my-app -``` - -It will create a directory called `my-app` inside the current folder.
-Inside that directory, it will generate the initial project structure and install the transitive dependencies: +npm start +# or with yarn +yarn create react-app my-app --scripts-version=react-scripts-ts +cd my-app +yarn start ``` -my-app/ - README.md - index.html - favicon.ico - node_modules/ - package.json - .gitignore - src/ - App.css - App.js - index.css - index.js - logo.svg -``` - -No configuration or complicated folder structures, just the files you need to build your app.
-Once the installation is done, you can run some commands inside the project folder: - -### `npm start` -Runs the app in development mode.
-Open [http://localhost:3000](http://localhost:3000) to view it in the browser. +*([npx](https://medium.com/@maybekatz/introducing-npx-an-npm-package-runner-55f7d4bd282b) comes with npm 5.2+ and higher, see [instructions for older npm versions](https://gist.github.com/gaearon/4064d3c23a77c74a3614c498a8bb1c5f))* -The page will reload if you make edits.
-You will see the build errors and lint warnings in the console. +Then open [http://localhost:3000/](http://localhost:3000/) to see your app.
+When you’re ready to deploy to production, create a minified bundle with `npm run build`. -Build errors +## Migration -### `npm run build` +In general, most upgrades won't require any migration steps to work, but if you experience problems after an upgrade, please file an issue, and we'll add it to the list of migration steps below. -Builds the app for production to the `build` folder.
-It correctly bundles React in production mode and optimizes the build for the best performance. +### From `<2.16.0` to `>=2.16.0` -The build is minified and the filenames include the hashes.
-Your app is ready to be deployed! +Since `2.16.0`, the template uses different `tsconfig` files for both development and production mode. For the latter, unfortunately, the path resolver is not smart enough to fall back to the basic `tsconfig.json` in case the expected `tsconfig.prod.json` is not present, so you have to create this file manually like shown [here](https://github.com/wmonk/create-react-app-typescript/blob/master/template/tsconfig.prod.json). -## User Guide +### From `<2.13.0` to `>=2.13.0` -The generated project will include a guide in its README.
-You can also read its latest version [here](https://github.com/facebookincubator/create-react-app/blob/master/template/README.md). +Since `2.13.0`, `typescript` is listed as a peer dependency of `react-scripts-ts`. For projects generated with at least this version, the init script takes care of properly installing it as dev dependency to the generated projects. Older projects require manual installation, in case you have not already done that. -## Philosophy +Using `npm`: +``` +npm i -D typescript +``` -* **One Dependency:** There is just one build dependency. It uses Webpack, Babel, ESLint, and other amazing projects, but provides a cohesive curated experience on top of them. +Using `yarn`: +``` +yarn add -D typescript +``` -* **Zero Configuration:** There are no configuration files or command line options. Configuring both development and production builds is handled for you so you can focus on writing code. +### From `<2.5.0` to `>=2.5.0` -* **No Lock-In:** You can “eject” to a custom setup at any time. Run a single command, and all the configuration and build dependencies will be moved directly into your project, so you can pick up right where you left off. +Version `2.5.0` introduces a new config file for jest, that is necessary for the tests to run. If you were previously running a version older than `v2.5.0` and upgraded to `v2.5.0` or newer, you need to manually add the new file, or else you'll get an error similar to this when trying to run your tests: -## Why Use This? +```javascript +Test suite failed to run -**If you’re getting started** with React, use `create-react-app` to automate the build of your app. There is no configuration file, and `react-scripts` is the only extra build dependency in your `package.json`. Your environment will have everything you need to build a modern React app: +{ + "messageText": "Cannot read file 'C:\\[project]\\tsconfig.test.json': ENOENT: no such file or directory, open 'C:\\[project]\\tsconfig.test.json'.", + "category": 1, + "code": 5012 +} +``` -* React, JSX, and ES6 support. -* Language extras beyond ES6 like the object spread operator. -* A dev server that lints for common errors. -* Import CSS and image files directly from JavaScript. -* Autoprefixed CSS, so you don’t need `-webkit` or other prefixes. -* A `build` script to bundle JS, CSS, and images for production, with sourcemaps. +To fix this, create a new file *in the root of the project* called `tsconfig.test.json`, and paste [the content of this file into it](https://raw.githubusercontent.com/wmonk/create-react-app-typescript/master/template/tsconfig.test.json). Everything should work now. For more info, please see [this issue](https://github.com/wmonk/create-react-app-typescript/issues/141). -**The feature set is intentionally limited**. It doesn’t support advanced features such as server rendering or CSS modules. Currently, it doesn’t support testing either. The tool is also **non-configurable** because it is hard to provide a cohesive experience and easy updates across a set of tools when the user can tweak anything. +## Changelog + +### 2.17.0 +* Update migration instructions - @DorianGrey +* tslint updates - @alexandrudanpop +* Stop eslint includes - @aurerua +* Resolve commited merge conflig - @AndrewKvalheim -**You don’t have to use this.** Historically it has been easy to [gradually adopt](https://www.youtube.com/watch?v=BF58ZJ1ZQxY) React. However many people create new single-page React apps from scratch every day. We’ve heard [loud](https://medium.com/@ericclemmons/javascript-fatigue-48d4011b6fc4) and [clear](https://twitter.com/thomasfuchs/status/708675139253174273) that this process can be error-prone and tedious, especially if this is your first JavaScript build stack. This project is an attempt to figure out a good way to start developing React apps. +### 2.16.0 +* Allow `moduleNameMapper` config override - @sebald +* Fix travis build - @DorianGrey +* Allow using different tsconfig file for dev and build - @DorianGrey + +### 2.15.1 +* Fix duplicated mjs entry in Jest config - @StevenLangbroek +* Allow `--watchAll` to be set - @DorianGrey + +### 2.15.0 +* Replace TSLint rules with presets - @nielsdB97 +* Update file-loader exclusion rules - @winstonewert +* Fix Uglifyjs settings - @meandmax +* Merge react-script 1.1.x - @wmonk -### Converting to a Custom Setup +### 2.14.0 +* README fixes - @kaminskypavel +* README fixes - @adambowles +* Remove unused JS files - @DorianGrey +* README fixes - @stephtr +* Added the abillity to import js and jsx files with ts-loader - @GeeWee +* Uglifyjs update for es6 support - @thetric -**If you’re a power user** and you aren’t happy with the default configuration, you can “eject” from the tool and use it as a boilerplate generator. +### 2.13.0 +* Remove tslint-loader from prod builds - @DorianGrey +* Include typescript as devDependency in boilerplate - @ianschmitz +* Document custom module formats - @joshtynjala +* Fix tsconfig.json - @diabelb -Running `npm run eject` copies all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. Commands like `npm start` and `npm run build` will still work, but they will point to the copied scripts so you can tweak them. At this point, you’re on your own. +### 2.12.0 +* Update typescript to 2.6.2 -**Note: this is a one-way operation. Once you `eject`, you can’t go back!** +### 2.11.0 +* Upgrade to [`react-scripts@1.0.17`](https://github.com/facebookincubator/create-react-app/releases/tag/v1.0.17) -You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. +### 2.10.0 +* README updates - StefanSchoof +* README updates - DorianGrey +* Add support for fork-ts-checker-webpack-plugin - johnnyreilly -## Limitations +### 2.9.0 - UNPUBLISHED +This included changes that were not published by the facebook upstream, so was unpublished. -Some features are currently **not supported**: +### 2.8.0 +* Update typescript to 2.5.3 - @nicolaserny -* Server rendering. -* Testing. -* Some experimental syntax extensions (e.g. decorators). -* CSS Modules. -* LESS or Sass. -* Hot reloading of components. +### 2.7.0 +* Merge react-scripts@1.0.13 - @JohnNilsson +* Fix git tempalte - @hktonylee +* Provide migration docs - @JReinhold +* Updated dependencies - @swengorschewski +* Fix tslint config - @comerc -Some of them might get added in the future if they are stable, are useful to majority of React apps, don’t conflict with existing tools, and don’t introduce additional configuration. +### 2.6.0 +* Merge react-scripts@1.0.10 - @wmonk +* Update component template - @pelotom -## What’s Inside? +### 2.5.0 +* Support dynamic imports - thanks @nicolaserny, @DorianGrey +* Fix up tsconfig - thanks @js-n +* Fix readme typo - thanks @adambowles +* Move to ts-jest - thanks @DorianGrey -The tools used by Create React App are subject to change. -Currently it is a thin layer on top of many amazing community projects, such as: +### 2.4.0 +* Upgrade typescript to 2.4 and ts-loader to 2.2.1 - thanks @frederickfogerty +* Fix readme typo - thanks @wrongway4you -* [webpack](https://webpack.github.io/) with [webpack-dev-server](https://github.com/webpack/webpack-dev-server), [html-webpack-plugin](https://github.com/ampedandwired/html-webpack-plugin) and [style-loader](https://github.com/webpack/style-loader) -* [Babel](http://babeljs.io/) with ES6 and extensions used by Facebook (JSX, [object spread](https://github.com/sebmarkbage/ecmascript-rest-spread/commits/master), [class properties](https://github.com/jeffmo/es-class-public-fields)) -* [Autoprefixer](https://github.com/postcss/autoprefixer) -* [ESLint](http://eslint.org/) -* and more. +### 2.3.2 +* Fix `typescript` version to 2.3.x until 2.4 @types are fixed -All of them are transitive dependencies of the provided npm package. +### 2.3.1 -## Contributing +* All tsc to parse config (for `extend`) - Thanks to @DorianGrey +* Fix various jest issues - thanks to @zinserjan +* Fix code coverage - thanks to @zinserjan -We'd love to have your helping hand on `create-react-app`! See [CONTRIBUTING.md](CONTRIBUTING.md) for more information on what we're looking for and how to get started. +### 2.2.0 +* Upgrade to [`react-scripts@1.0.6`](https://github.com/facebookincubator/create-react-app/) -## Acknowledgements +### 2.1.0 +* Update to `tslint@5.2.0` - thanks to @mindjuice +* Fix test setup issue - thanks to @jonmpqts +* Add `source-map-loader` - thanks to @Place1 +* Update to `typescript@2.3.3` - thanks to @sjdweb -We are grateful to the authors of existing related projects for their ideas and collaboration: +### 2.0.1 +* Fix issue with jest finding test files -* [@eanplatter](https://github.com/eanplatter) -* [@insin](https://github.com/insin) -* [@mxstbr](https://github.com/mxstbr) +### 2.0.0 +* Upgrade to [`react-scripts@1.x.x`](https://github.com/facebookincubator/create-react-app/blob/0d1521aabf5a0201ea1bcccc33e286afe048f820/CHANGELOG.md) + +### 1.4.0 +* Upgrade to typescript@2.3.2 - thanks to @patrick91 +* Add tests around react-scripts-ts - thanks to @migerh + +### 1.3.0 +* Upgrade to typescript@2.2.2 - thanks to @jeremistadler + +### 1.1.8 +* Fix regression where no `@types` were being installed on init + +### 1.1.7 +* Merge facebookincubator/create-react-app@0.9.5 into react-scripts-ts +* Merge facebookincubator/create-react-app@0.9.4 into react-scripts-ts +* Merge facebookincubator/create-react-app@0.9.3 into react-scripts-ts +* Merge facebookincubator/create-react-app@0.9.2 into react-scripts-ts +* Merge facebookincubator/create-react-app@0.9.1 into react-scripts-ts + +### 1.1.6 +* Merge facebookincubator/create-react-app@0.9.0 into react-scripts-ts + +### 1.0.6 +* Add missing `cli-highlight` dependency -## Alternatives +### 1.0.5 +* Print file names when running `npm run build` +* Add support for `setupTest.ts` +* Highlight source code when erroring in `npm run build` -If you don’t agree with the choices made in this project, you might want to explore alternatives with different tradeoffs: +### 1.0.4 +* Change mentions of `eslint` to `tslint` -* [enclave](https://github.com/eanplatter/enclave) -* [nwb](https://github.com/insin/nwb) -* [motion](https://github.com/motion/motion) -* [rackt-cli](https://github.com/mzabriskie/rackt-cli) -* [budō](https://github.com/mattdesl/budo) -* [rwb](https://github.com/petehunt/rwb) -* [quik](https://github.com/satya164/quik) -* [sagui](https://github.com/saguijs/sagui) -* [roc](https://github.com/rocjs/roc) -* [aik](https://github.com/d4rkr00t/aik) -* [react-app](https://github.com/kriasoft/react-app) -* [dev-toolkit](https://github.com/stoikerty/dev-toolkit) -* [mozilla-neo](https://github.com/mozilla/neo) -* [tarec](https://github.com/geowarin/tarec) +### 1.0.3 +* Remove hidden character from `tsconfig.json` -You can also use module bundlers like [webpack](http://webpack.github.io) and [Browserify](http://browserify.org/) directly.
-React documentation includes [a walkthrough](https://facebook.github.io/react/docs/package-management.html) on this topic. +### 1.0.2 +* Copy `typescriptTransform.js` when running `npm run eject` diff --git a/bin/react-scripts-ts.js b/bin/react-scripts-ts.js new file mode 100755 index 000000000..a4d1b11b1 --- /dev/null +++ b/bin/react-scripts-ts.js @@ -0,0 +1,55 @@ +#!/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. + */ + +'use strict'; + +const spawn = require('react-dev-utils/crossSpawn'); +const args = process.argv.slice(2); + +const scriptIndex = args.findIndex( + x => x === 'build' || x === 'eject' || x === 'start' || x === 'test' +); +const script = scriptIndex === -1 ? args[0] : args[scriptIndex]; +const nodeArgs = scriptIndex > 0 ? args.slice(0, scriptIndex) : []; + +switch (script) { + case 'build': + case 'eject': + case 'start': + case 'test': { + const result = spawn.sync( + 'node', + nodeArgs + .concat(require.resolve('../scripts/' + script)) + .concat(args.slice(scriptIndex + 1)), + { stdio: 'inherit' } + ); + if (result.signal) { + if (result.signal === 'SIGKILL') { + console.log( + 'The build failed because the process exited too early. ' + + 'This probably means the system ran out of memory or someone called ' + + '`kill -9` on the process.' + ); + } else if (result.signal === 'SIGTERM') { + console.log( + 'The build failed because the process exited too early. ' + + 'Someone might have called `kill` or `killall`, or the system could ' + + 'be shutting down.' + ); + } + process.exit(1); + } + process.exit(result.status); + break; + } + default: + console.log('Unknown script "' + script + '".'); + console.log('Perhaps you need to update react-scripts-ts?'); + break; +} diff --git a/bin/react-scripts.js b/bin/react-scripts.js deleted file mode 100755 index 583818339..000000000 --- a/bin/react-scripts.js +++ /dev/null @@ -1,22 +0,0 @@ -#!/usr/bin/env node -var spawn = require('cross-spawn'); -var script = process.argv[2]; -var args = process.argv.slice(3); - -switch (script) { -case 'build': -case 'eject': -case 'start': -case 'test': - var result = spawn.sync( - 'node', - [require.resolve('../scripts/' + script)].concat(args), - {stdio: 'inherit'} - ); - process.exit(result.status); - break; -default: - console.log('Unknown script "' + script + '".'); - console.log('Perhaps you need to update react-scripts?'); - break; -} diff --git a/config/babel.dev.js b/config/babel.dev.js deleted file mode 100644 index 565331090..000000000 --- a/config/babel.dev.js +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Copyright (c) 2015-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - */ - -module.exports = { - // Don't try to find .babelrc because we want to force this configuration. - babelrc: false, - // This is a feature of `babel-loader` for webpack (not Babel itself). - // It enables caching results in OS temporary directory for faster rebuilds. - cacheDirectory: true, - presets: [ - // Latest stable ECMAScript features - require.resolve('babel-preset-latest'), - // JSX, Flow - require.resolve('babel-preset-react') - ], - plugins: [ - // class { handleClick = () => { } } - require.resolve('babel-plugin-transform-class-properties'), - // { ...todo, completed: true } - require.resolve('babel-plugin-transform-object-rest-spread'), - // function* () { yield 42; yield 43; } - [require.resolve('babel-plugin-transform-regenerator'), { - // Async functions are converted to generators by babel-preset-latest - async: false - }], - // Polyfills the runtime needed for async/await and generators - [require.resolve('babel-plugin-transform-runtime'), { - helpers: false, - polyfill: false, - regenerator: true - }] - ] -}; diff --git a/config/babel.prod.js b/config/babel.prod.js deleted file mode 100644 index 32f4bd665..000000000 --- a/config/babel.prod.js +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Copyright (c) 2015-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - */ - -module.exports = { - // Don't try to find .babelrc because we want to force this configuration. - babelrc: false, - presets: [ - // Latest stable ECMAScript features - require.resolve('babel-preset-latest'), - // JSX, Flow - require.resolve('babel-preset-react') - ], - plugins: [ - // class { handleClick = () => { } } - require.resolve('babel-plugin-transform-class-properties'), - // { ...todo, completed: true } - require.resolve('babel-plugin-transform-object-rest-spread'), - // function* () { yield 42; yield 43; } - [require.resolve('babel-plugin-transform-regenerator'), { - // Async functions are converted to generators by babel-preset-latest - async: false - }], - // Polyfills the runtime needed for async/await and generators - [require.resolve('babel-plugin-transform-runtime'), { - helpers: false, - polyfill: false, - regenerator: true - }], - // Optimization: hoist JSX that never changes out of render() - require.resolve('babel-plugin-transform-react-constant-elements') - ] -}; diff --git a/config/env.js b/config/env.js index cfa10c75b..7793fadf0 100644 --- a/config/env.js +++ b/config/env.js @@ -1,24 +1,104 @@ +// @remove-on-eject-begin /** * Copyright (c) 2015-present, Facebook, Inc. - * All rights reserved. * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * 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 fs = require('fs'); +const path = require('path'); +const paths = require('./paths'); + +// Make sure that including paths.js after env.js will read .env variables. +delete require.cache[require.resolve('./paths')]; + +const NODE_ENV = process.env.NODE_ENV; +if (!NODE_ENV) { + throw new Error( + 'The NODE_ENV environment variable is required but was not specified.' + ); +} + +// https://github.com/bkeepers/dotenv#what-other-env-files-can-i-use +var dotenvFiles = [ + `${paths.dotenv}.${NODE_ENV}.local`, + `${paths.dotenv}.${NODE_ENV}`, + // Don't include `.env.local` for `test` environment + // since normally you expect tests to produce the same + // results for everyone + NODE_ENV !== 'test' && `${paths.dotenv}.local`, + paths.dotenv, +].filter(Boolean); + +// Load environment variables from .env* files. Suppress warnings using silent +// if this file is missing. dotenv will never modify any environment variables +// that have already been set. Variable expansion is supported in .env files. +// https://github.com/motdotla/dotenv +// https://github.com/motdotla/dotenv-expand +dotenvFiles.forEach(dotenvFile => { + if (fs.existsSync(dotenvFile)) { + require('dotenv-expand')( + require('dotenv').config({ + path: dotenvFile, + }) + ); + } +}); + +// We support resolving modules according to `NODE_PATH`. +// This lets you use absolute paths in imports inside large monorepos: +// https://github.com/facebookincubator/create-react-app/issues/253. +// It works similar to `NODE_PATH` in Node itself: +// https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders +// Note that unlike in Node, only *relative* paths from `NODE_PATH` are honored. +// Otherwise, we risk importing Node.js core modules into an app instead of Webpack shims. +// https://github.com/facebookincubator/create-react-app/issues/1023#issuecomment-265344421 +// We also resolve them to make sure all tools using them work consistently. +const appDirectory = fs.realpathSync(process.cwd()); +process.env.NODE_PATH = (process.env.NODE_PATH || '') + .split(path.delimiter) + .filter(folder => folder && !path.isAbsolute(folder)) + .map(folder => path.resolve(appDirectory, folder)) + .join(path.delimiter); // Grab NODE_ENV and REACT_APP_* environment variables and prepare them to be // injected into the application via DefinePlugin in Webpack configuration. +const REACT_APP = /^REACT_APP_/i; + +function getClientEnvironment(publicUrl) { + const raw = Object.keys(process.env) + .filter(key => REACT_APP.test(key)) + .reduce( + (env, key) => { + env[key] = process.env[key]; + return env; + }, + { + // Useful for determining whether we’re running in production mode. + // Most importantly, it switches React into the correct mode. + NODE_ENV: process.env.NODE_ENV || 'development', + // Useful for resolving the correct path to static assets in `public`. + // For example, . + // This should only be used as an escape hatch. Normally you would put + // images into the `src` and `import` them in code to get their paths. + PUBLIC_URL: publicUrl, + } + ); + // Stringify all values so we can feed into Webpack DefinePlugin + const stringified = { + 'process.env': Object.keys(raw).reduce( + (env, key) => { + env[key] = JSON.stringify(raw[key]); + return env; + }, + {} + ), + }; + + return { raw, stringified }; +} -var REACT_APP = /^REACT_APP_/i; -var NODE_ENV = JSON.stringify(process.env.NODE_ENV || 'development'); - -module.exports = Object - .keys(process.env) - .filter(key => REACT_APP.test(key)) - .reduce((env, key) => { - env['process.env.' + key] = JSON.stringify(process.env[key]); - return env; - }, { - 'process.env.NODE_ENV': NODE_ENV - }); +module.exports = getClientEnvironment; diff --git a/config/eslint.js b/config/eslint.js deleted file mode 100644 index 8eaeacbd7..000000000 --- a/config/eslint.js +++ /dev/null @@ -1,204 +0,0 @@ -/** - * Copyright (c) 2015-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - */ - -// Inspired by https://github.com/airbnb/javascript but less opinionated. - -// We use eslint-loader so even warnings are very visibile. -// This is why we only use "WARNING" level for potential errors, -// and we don't use "ERROR" level at all. - -// In the future, we might create a separate list of rules for production. -// It would probably be more strict. - -module.exports = { - root: true, - - parser: 'babel-eslint', - - // import plugin is temporarily disabled, scroll below to see why - plugins: [/*'import', */'flowtype', 'jsx-a11y', 'react'], - - env: { - browser: true, - commonjs: true, - es6: true, - jest: true, - node: true - }, - - parserOptions: { - ecmaVersion: 6, - sourceType: 'module', - ecmaFeatures: { - jsx: true, - generators: true, - experimentalObjectRestSpread: true - } - }, - - settings: { - 'import/ignore': [ - 'node_modules', - '\\.(json|css|jpg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm)$', - ], - 'import/extensions': ['.js'], - 'import/resolver': { - node: { - extensions: ['.js', '.json'] - } - } - }, - - rules: { - // http://eslint.org/docs/rules/ - 'array-callback-return': 'warn', - 'default-case': ['warn', { commentPattern: '^no default$' }], - 'dot-location': ['warn', 'property'], - eqeqeq: ['warn', 'allow-null'], - 'guard-for-in': 'warn', - 'new-parens': 'warn', - 'no-array-constructor': 'warn', - 'no-caller': 'warn', - 'no-cond-assign': ['warn', 'always'], - 'no-const-assign': 'warn', - 'no-control-regex': 'warn', - 'no-delete-var': 'warn', - 'no-dupe-args': 'warn', - 'no-dupe-class-members': 'warn', - 'no-dupe-keys': 'warn', - 'no-duplicate-case': 'warn', - 'no-empty-character-class': 'warn', - 'no-empty-pattern': 'warn', - 'no-eval': 'warn', - 'no-ex-assign': 'warn', - 'no-extend-native': 'warn', - 'no-extra-bind': 'warn', - 'no-extra-label': 'warn', - 'no-fallthrough': 'warn', - 'no-func-assign': 'warn', - 'no-implied-eval': 'warn', - 'no-invalid-regexp': 'warn', - 'no-iterator': 'warn', - 'no-label-var': 'warn', - 'no-labels': ['warn', { allowLoop: false, allowSwitch: false }], - 'no-lone-blocks': 'warn', - 'no-loop-func': 'warn', - 'no-mixed-operators': ['warn', { - groups: [ - ['&', '|', '^', '~', '<<', '>>', '>>>'], - ['==', '!=', '===', '!==', '>', '>=', '<', '<='], - ['&&', '||'], - ['in', 'instanceof'] - ], - allowSamePrecedence: false - }], - 'no-multi-str': 'warn', - 'no-native-reassign': 'warn', - 'no-negated-in-lhs': 'warn', - 'no-new-func': 'warn', - 'no-new-object': 'warn', - 'no-new-symbol': 'warn', - 'no-new-wrappers': 'warn', - 'no-obj-calls': 'warn', - 'no-octal': 'warn', - 'no-octal-escape': 'warn', - 'no-redeclare': 'warn', - 'no-regex-spaces': 'warn', - 'no-restricted-syntax': [ - 'warn', - 'LabeledStatement', - 'WithStatement', - ], - 'no-script-url': 'warn', - 'no-self-assign': 'warn', - 'no-self-compare': 'warn', - 'no-sequences': 'warn', - 'no-shadow-restricted-names': 'warn', - 'no-sparse-arrays': 'warn', - 'no-this-before-super': 'warn', - 'no-throw-literal': 'warn', - 'no-undef': 'warn', - 'no-unexpected-multiline': 'warn', - 'no-unreachable': 'warn', - 'no-unused-expressions': 'warn', - 'no-unused-labels': 'warn', - 'no-unused-vars': ['warn', { vars: 'local', args: 'none' }], - 'no-use-before-define': ['warn', 'nofunc'], - 'no-useless-computed-key': 'warn', - 'no-useless-concat': 'warn', - 'no-useless-constructor': 'warn', - 'no-useless-escape': 'warn', - 'no-useless-rename': ['warn', { - ignoreDestructuring: false, - ignoreImport: false, - ignoreExport: false, - }], - 'no-with': 'warn', - 'no-whitespace-before-property': 'warn', - 'operator-assignment': ['warn', 'always'], - radix: 'warn', - 'require-yield': 'warn', - 'rest-spread-spacing': ['warn', 'never'], - strict: ['warn', 'never'], - 'unicode-bom': ['warn', 'never'], - 'use-isnan': 'warn', - 'valid-typeof': 'warn', - - // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/ - - // TODO: import rules are temporarily disabled because they don't play well - // with how eslint-loader only checks the file you change. So if module A - // imports module B, and B is missing a default export, the linter will - // record this as an issue in module A. Now if you fix module B, the linter - // will not be aware that it needs to re-lint A as well, so the error - // will stay until the next restart, which is really confusing. - - // This is probably fixable with a patch to eslint-loader. - // When file A is saved, we want to invalidate all files that import it - // *and* that currently have lint errors. This should fix the problem. - - // 'import/default': 'warn', - // 'import/export': 'warn', - // 'import/named': 'warn', - // 'import/namespace': 'warn', - // 'import/no-amd': 'warn', - // 'import/no-duplicates': 'warn', - // 'import/no-extraneous-dependencies': 'warn', - // 'import/no-named-as-default': 'warn', - // 'import/no-named-as-default-member': 'warn', - // 'import/no-unresolved': ['warn', { commonjs: true }], - - // https://github.com/yannickcr/eslint-plugin-react/tree/master/docs/rules - 'react/jsx-equals-spacing': ['warn', 'never'], - 'react/jsx-no-duplicate-props': ['warn', { ignoreCase: true }], - 'react/jsx-no-undef': 'warn', - 'react/jsx-pascal-case': ['warn', { - allowAllCaps: true, - ignore: [], - }], - 'react/jsx-uses-react': 'warn', - 'react/jsx-uses-vars': 'warn', - 'react/no-deprecated': 'warn', - 'react/no-direct-mutation-state': 'warn', - 'react/no-is-mounted': 'warn', - 'react/react-in-jsx-scope': 'warn', - 'react/require-render-return': 'warn', - - // https://github.com/evcohen/eslint-plugin-jsx-a11y/tree/master/docs/rules - 'jsx-a11y/aria-role': 'warn', - 'jsx-a11y/img-has-alt': 'warn', - 'jsx-a11y/img-redundant-alt': 'warn', - 'jsx-a11y/no-access-key': 'warn', - - // https://github.com/gajus/eslint-plugin-flowtype - 'flowtype/define-flow-type': 'warn', - 'flowtype/require-valid-file-annotation': 'warn', - 'flowtype/use-flow-type': 'warn' - } -}; diff --git a/config/flow/css.js.flow b/config/flow/css.js.flow deleted file mode 100644 index 46e7f7c04..000000000 --- a/config/flow/css.js.flow +++ /dev/null @@ -1 +0,0 @@ -// @flow diff --git a/config/flow/file.js.flow b/config/flow/file.js.flow deleted file mode 100644 index 701b6700f..000000000 --- a/config/flow/file.js.flow +++ /dev/null @@ -1,2 +0,0 @@ -// @flow -declare export default string; diff --git a/config/jest/CSSStub.js b/config/jest/CSSStub.js deleted file mode 100644 index 05fb9d0d7..000000000 --- a/config/jest/CSSStub.js +++ /dev/null @@ -1,11 +0,0 @@ -/** - * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @flow - */ - -module.exports = {}; diff --git a/config/jest/FileStub.js b/config/jest/FileStub.js deleted file mode 100644 index 96d28629f..000000000 --- a/config/jest/FileStub.js +++ /dev/null @@ -1,11 +0,0 @@ -/** - * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @flow - */ - -module.exports = "test-file-stub"; diff --git a/config/jest/babelTransform.js b/config/jest/babelTransform.js new file mode 100644 index 000000000..02742e90c --- /dev/null +++ b/config/jest/babelTransform.js @@ -0,0 +1,15 @@ +// @remove-file-on-eject +/** + * Copyright (c) 2014-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 babelJest = require('babel-jest'); + +module.exports = babelJest.createTransformer({ + presets: [require.resolve('babel-preset-react-app')], + babelrc: false, +}); diff --git a/config/jest/cssTransform.js b/config/jest/cssTransform.js new file mode 100644 index 000000000..59053068f --- /dev/null +++ b/config/jest/cssTransform.js @@ -0,0 +1,22 @@ +// @remove-on-eject-begin +/** + * Copyright (c) 2014-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'; + +// This is a custom Jest transformer turning style imports into empty objects. +// http://facebook.github.io/jest/docs/en/webpack.html + +module.exports = { + process() { + return 'module.exports = {};'; + }, + getCacheKey() { + // The output is always the same. + return 'cssTransform'; + }, +}; diff --git a/config/jest/fileTransform.js b/config/jest/fileTransform.js new file mode 100644 index 000000000..38910e18b --- /dev/null +++ b/config/jest/fileTransform.js @@ -0,0 +1,20 @@ +// @remove-on-eject-begin +/** + * Copyright (c) 2014-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 path = require('path'); + +// This is a custom Jest transformer turning file imports into filenames. +// http://facebook.github.io/jest/docs/en/webpack.html + +module.exports = { + process(src, filename) { + return `module.exports = ${JSON.stringify(path.basename(filename))};`; + }, +}; diff --git a/config/jest/transform.js b/config/jest/transform.js deleted file mode 100644 index 9f51b1a85..000000000 --- a/config/jest/transform.js +++ /dev/null @@ -1,12 +0,0 @@ -/** - * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - */ - -const babelDev = require('../babel.dev'); -const babelJest = require('babel-jest'); - -module.exports = babelJest.createTransformer(babelDev); diff --git a/config/jest/typescriptTransform.js b/config/jest/typescriptTransform.js new file mode 100644 index 000000000..9b138ac8e --- /dev/null +++ b/config/jest/typescriptTransform.js @@ -0,0 +1,7 @@ +// Copyright 2004-present Facebook. All Rights Reserved. + +'use strict'; + +const tsJestPreprocessor = require('ts-jest/preprocessor'); + +module.exports = tsJestPreprocessor; diff --git a/config/paths.js b/config/paths.js index e6f2ff6cb..cc6891d6a 100644 --- a/config/paths.js +++ b/config/paths.js @@ -1,65 +1,128 @@ +// @remove-on-eject-begin /** * Copyright (c) 2015-present, Facebook, Inc. - * All rights reserved. * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * 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'; -// TODO: we can split this file into several files (pre-eject, post-eject, test) -// and use those instead. This way we don't need to branch here. +const path = require('path'); +const fs = require('fs'); +const url = require('url'); -var path = require('path'); +// Make sure any symlinks in the project folder are resolved: +// https://github.com/facebookincubator/create-react-app/issues/637 +const appDirectory = fs.realpathSync(process.cwd()); +const resolveApp = relativePath => path.resolve(appDirectory, relativePath); -// True after ejecting, false when used as a dependency -var isEjected = ( - path.resolve(path.join(__dirname, '..')) === - path.resolve(process.cwd()) -); +const envPublicUrl = process.env.PUBLIC_URL; -// Are we developing create-react-app locally? -var isInCreateReactAppSource = ( - process.argv.some(arg => arg.indexOf('--debug-template') > -1) -); - -function resolveOwn(relativePath) { - return path.resolve(__dirname, relativePath); +function ensureSlash(path, needsSlash) { + const hasSlash = path.endsWith('/'); + if (hasSlash && !needsSlash) { + return path.substr(path, path.length - 1); + } else if (!hasSlash && needsSlash) { + return `${path}/`; + } else { + return path; + } } -function resolveApp(relativePath) { - return path.resolve(relativePath); +const getPublicUrl = appPackageJson => + envPublicUrl || require(appPackageJson).homepage; + +// We use `PUBLIC_URL` environment variable or "homepage" field to infer +// "public path" at which the app is served. +// Webpack needs to know it to put the right +``` + +Then, on the server, you can replace `__SERVER_DATA__` with a JSON of real data right before sending the response. The client code can then read `window.SERVER_DATA` to use it. **Make sure to [sanitize the JSON before sending it to the client](https://medium.com/node-security/the-most-common-xss-vulnerability-in-react-js-applications-2bdffbcc1fa0) as it makes your app vulnerable to XSS attacks.** + +## Running Tests + +>Note: this feature is available with `react-scripts@0.3.0` and higher.
+>[Read the migration guide to learn how to enable it in older projects!](https://github.com/facebookincubator/create-react-app/blob/master/CHANGELOG.md#migrating-from-023-to-030) + +Create React App uses [Jest](https://facebook.github.io/jest/) as its test runner. To prepare for this integration, we did a [major revamp](https://facebook.github.io/jest/blog/2016/09/01/jest-15.html) of Jest so if you heard bad things about it years ago, give it another try. + +Jest is a Node-based runner. This means that the tests always run in a Node environment and not in a real browser. This lets us enable fast iteration speed and prevent flakiness. + +While Jest provides browser globals such as `window` thanks to [jsdom](https://github.com/tmpvar/jsdom), they are only approximations of the real browser behavior. Jest is intended to be used for unit tests of your logic and your components rather than the DOM quirks. + +We recommend that you use a separate tool for browser end-to-end tests if you need them. They are beyond the scope of Create React App. + +### Filename Conventions + +Jest will look for test files with any of the following popular naming conventions: + +* Files with `.js` suffix in `__tests__` folders. +* Files with `.test.js` suffix. +* Files with `.spec.js` suffix. + +The `.test.js` / `.spec.js` files (or the `__tests__` folders) can be located at any depth under the `src` top level folder. + +We recommend to put the test files (or `__tests__` folders) next to the code they are testing so that relative imports appear shorter. For example, if `App.test.js` and `App.js` are in the same folder, the test just needs to `import App from './App'` instead of a long relative path. Colocation also helps find tests more quickly in larger projects. + +### Command Line Interface + +When you run `npm test`, Jest will launch in the watch mode. Every time you save a file, it will re-run the tests, just like `npm start` recompiles the code. + +The watcher includes an interactive command-line interface with the ability to run all tests, or focus on a search pattern. It is designed this way so that you can keep it open and enjoy fast re-runs. You can learn the commands from the “Watch Usage” note that the watcher prints after every run: + +![Jest watch mode](http://facebook.github.io/jest/img/blog/15-watch.gif) + +### Version Control Integration + +By default, when you run `npm test`, Jest will only run the tests related to files changed since the last commit. This is an optimization designed to make your tests run fast regardless of how many tests you have. However it assumes that you don’t often commit the code that doesn’t pass the tests. + +Jest will always explicitly mention that it only ran tests related to the files changed since the last commit. You can also press `a` in the watch mode to force Jest to run all tests. + +Jest will always run all tests on a [continuous integration](#continuous-integration) server or if the project is not inside a Git or Mercurial repository. + +### Writing Tests + +To create tests, add `it()` (or `test()`) blocks with the name of the test and its code. You may optionally wrap them in `describe()` blocks for logical grouping but this is neither required nor recommended. + +Jest provides a built-in `expect()` global function for making assertions. A basic test could look like this: + +```js +import sum from './sum'; + +it('sums numbers', () => { + expect(sum(1, 2)).toEqual(3); + expect(sum(2, 2)).toEqual(4); +}); +``` + +All `expect()` matchers supported by Jest are [extensively documented here](http://facebook.github.io/jest/docs/expect.html).
+You can also use [`jest.fn()` and `expect(fn).toBeCalled()`](http://facebook.github.io/jest/docs/expect.html#tohavebeencalled) to create “spies” or mock functions. + +### Testing Components + +There is a broad spectrum of component testing techniques. They range from a “smoke test” verifying that a component renders without throwing, to shallow rendering and testing some of the output, to full rendering and testing component lifecycle and state changes. + +Different projects choose different testing tradeoffs based on how often components change, and how much logic they contain. If you haven’t decided on a testing strategy yet, we recommend that you start with creating simple smoke tests for your components: + +```ts +import * as React from 'react'; +import * as ReactDOM from 'react-dom'; +import App from './App'; + +it('renders without crashing', () => { + const div = document.createElement('div'); + ReactDOM.render(, div); +}); +``` + +This test mounts a component and makes sure that it didn’t throw during rendering. Tests like this provide a lot of value with very little effort so they are great as a starting point, and this is the test you will find in `src/App.test.tsx`. + +When you encounter bugs caused by changing components, you will gain a deeper insight into which parts of them are worth testing in your application. This might be a good time to introduce more specific tests asserting specific expected output or behavior. + +If you’d like to test components in isolation from the child components they render, we recommend using [`shallow()` rendering API](http://airbnb.io/enzyme/docs/api/shallow.html) from [Enzyme](http://airbnb.io/enzyme/). To install it, run: + +```sh +npm install --save-dev enzyme @types/enzyme enzyme-adapter-react-16 @types/enzyme-adapter-react-16 react-test-renderer @types/react-test-renderer +``` + +Alternatively you may use `yarn`: + +```sh +yarn add --dev enzyme @types/enzyme enzyme-adapter-react-16 @types/enzyme-adapter-react-16 react-test-renderer @types/react-test-renderer +``` + +#### `src/setupTests.ts` +```ts +import * as Enzyme from 'enzyme'; +import * as Adapter from 'enzyme-adapter-react-16'; + +Enzyme.configure({ adapter: new Adapter() }); +``` + +>Note: Keep in mind that if you decide to "eject" before creating `src/setupTests.js`, the resulting `package.json` file won't contain any reference to it. [Read here](#initializing-test-environment) to learn how to add this after ejecting. + +Now you can write a smoke test with it: + +```ts +import * as React from 'react'; +import { shallow } from 'enzyme'; +import App from './App'; + +it('renders without crashing', () => { + shallow(); +}); +``` + +Unlike the previous smoke test using `ReactDOM.render()`, this test only renders `` and doesn’t go deeper. For example, even if `` itself renders a `