├── .all-contributorsrc
├── .editorconfig
├── .eslintignore
├── .eslintrc.js
├── .github
├── FUNDING.yml
├── ISSUE_TEMPLATE
│ ├── bug_report.md
│ └── feature_request.md
└── workflows
│ ├── npm-publish.yml
│ └── pull-request.yml
├── .gitignore
├── .husky
└── pre-commit
├── .prettierrc.js
├── .versionrc.js
├── CHANGELOG.md
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── _config.yml
├── assets
└── readme.gif
├── clean.js
├── example
├── README.md
├── package-lock.json
├── package.json
├── public
│ ├── index.html
│ └── manifest.json
└── src
│ ├── App.jsx
│ └── index.jsx
├── package.json
├── pull_request_template.md
├── react-use-downloader.code-workspace
├── rollup.config.js
├── src
├── __tests__
│ └── index.spec.ts
├── index.ts
├── react-app-env.d.ts
└── types.ts
├── tsconfig.json
├── tsconfig.test.json
└── yarn.lock
/.all-contributorsrc:
--------------------------------------------------------------------------------
1 | {
2 | "files": ["README.md"],
3 | "imageSize": 100,
4 | "commit": false,
5 | "contributors": [
6 | {
7 | "login": "esemeniuc",
8 | "name": "Eric Semeniuc",
9 | "avatar_url": "https://avatars.githubusercontent.com/u/3838856?v=4",
10 | "profile": "https://semeniuc.ml/",
11 | "contributions": ["ideas"]
12 | },
13 | {
14 | "login": "davdi1337",
15 | "name": "davdi1337",
16 | "avatar_url": "https://avatars.githubusercontent.com/u/66253422?v=4",
17 | "profile": "https://github.com/davdi1337",
18 | "contributions": ["code", "bug"]
19 | },
20 | {
21 | "login": "mastepanoski",
22 | "name": "Mauro Stepanoski",
23 | "avatar_url": "https://avatars.githubusercontent.com/u/7851219?v=4",
24 | "profile": "https://heliusit.net",
25 | "contributions": ["ideas", "code"]
26 | },
27 | {
28 | "login": "bzbetty",
29 | "name": "Sam \"Betty\" McKoy",
30 | "avatar_url": "https://avatars.githubusercontent.com/u/533131?v=4",
31 | "profile": "http://bzbetty.blogspot.com",
32 | "contributions": ["bug"]
33 | },
34 | {
35 | "login": "peranosborn",
36 | "name": "Peran Osborn",
37 | "avatar_url": "https://avatars.githubusercontent.com/u/1318002?v=4",
38 | "profile": "https://github.com/peranosborn",
39 | "contributions": ["bug", "ideas"]
40 | },
41 | {
42 | "login": "MarcosRS",
43 | "name": "Marcos",
44 | "avatar_url": "https://avatars.githubusercontent.com/u/12486814?v=4",
45 | "profile": "https://github.com/MarcosRS",
46 | "contributions": ["bug", "ideas"]
47 | },
48 | {
49 | "login": "9swampy",
50 | "name": "9swampy",
51 | "avatar_url": "https://avatars.githubusercontent.com/u/523054?v=4",
52 | "profile": "https://github.com/9swampy",
53 | "contributions": ["bug", "code"]
54 | },
55 | {
56 | "login": "davecarlson",
57 | "name": "Dave Carlson",
58 | "avatar_url": "https://avatars.githubusercontent.com/u/299702?v=4",
59 | "profile": "https://github.com/davecarlson",
60 | "contributions": ["ideas"]
61 | },
62 | {
63 | "login": "ruru-ink",
64 | "name": "Phil Taylor",
65 | "avatar_url": "https://avatars.githubusercontent.com/u/1455736?v=4",
66 | "profile": "http://moa-crypto.com/",
67 | "contributions": ["maintenance"]
68 | },
69 | {
70 | "login": "MarcRoemmelt",
71 | "name": "Marc Römmelt",
72 | "avatar_url": "https://avatars.githubusercontent.com/u/36316710?v=4",
73 | "profile": "https://github.com/MarcRoemmelt",
74 | "contributions": ["ideas", "code"]
75 | },
76 | {
77 | "login": "nik-webdevelop",
78 | "name": "nik-webdevelop",
79 | "avatar_url": "https://avatars.githubusercontent.com/u/10981702?v=4",
80 | "profile": "https://github.com/nik-webdevelop",
81 | "contributions": ["ideas"]
82 | }
83 | ],
84 | "contributorsPerLine": 7,
85 | "projectName": "react-use-downloader",
86 | "projectOwner": "the-bugging",
87 | "repoType": "github",
88 | "repoHost": "https://github.com",
89 | "skipCi": true,
90 | "commitConvention": "angular",
91 | "commitType": "docs"
92 | }
93 |
94 |
--------------------------------------------------------------------------------
/.editorconfig:
--------------------------------------------------------------------------------
1 | root = true
2 |
3 | [*]
4 | charset = utf-8
5 | indent_style = space
6 | indent_size = 2
7 | end_of_line = lf
8 | insert_final_newline = true
9 | trim_trailing_whitespace = true
10 |
--------------------------------------------------------------------------------
/.eslintignore:
--------------------------------------------------------------------------------
1 | example/*/**
--------------------------------------------------------------------------------
/.eslintrc.js:
--------------------------------------------------------------------------------
1 | /* eslint-disable prettier/prettier */
2 | module.exports = {
3 | env: {
4 | browser: true,
5 | es2020: true,
6 | },
7 | extends: [
8 | 'plugin:react/recommended',
9 | 'airbnb',
10 | 'plugin:prettier/recommended',
11 | 'plugin:@typescript-eslint/eslint-recommended',
12 | 'plugin:@typescript-eslint/recommended',
13 | ],
14 | parser: '@typescript-eslint/parser',
15 | parserOptions: {
16 | ecmaFeatures: {
17 | jsx: true,
18 | },
19 | ecmaVersion: 11,
20 | sourceType: 'module',
21 | },
22 | plugins: ['react', 'react-hooks', '@typescript-eslint', 'prettier'],
23 | settings: {
24 | 'import/resolver': {
25 | node: {
26 | extensions: ['.ts', '.tsx', '.json'],
27 | },
28 | },
29 | },
30 | rules: {
31 | 'react-hooks/rules-of-hooks': 'error',
32 | 'react-hooks/exhaustive-deps': 'error',
33 | '@typescript-eslint/explicit-function-return-type': 'off',
34 | 'react/jsx-filename-extension': ['error', { extensions: ['.tsx'] }],
35 | 'react/prop-types': 'off',
36 | 'react/jsx-one-expression-per-line': 'off',
37 | 'import/extensions': 0,
38 | 'import/prefer-default-export': 'off',
39 | 'import/no-unresolved': ['error', { ignore: ['react-hooks-fetch'] }],
40 | camelcase: [
41 | 'error',
42 | {
43 | properties: 'never',
44 | ignoreDestructuring: false,
45 | allow: ['first_name'],
46 | },
47 | ],
48 | 'react/state-in-constructor': 'off',
49 | 'no-console': 'off',
50 | 'react/react-in-jsx-scope': 'off',
51 | },
52 | };
53 |
--------------------------------------------------------------------------------
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | github: [the-bugging]
2 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug report
3 | about: Create a report to help us improve
4 | title: ''
5 | labels: ''
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Describe the bug**
11 | A clear and concise description of what the bug is.
12 |
13 | **To Reproduce**
14 | Steps to reproduce the behavior:
15 | 1. Go to '...'
16 | 2. Click on '....'
17 | 3. Scroll down to '....'
18 | 4. See error
19 |
20 | **Additional context**
21 | Add any other context about the problem here.
22 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/feature_request.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Feature request
3 | about: Suggest an idea for this project
4 | title: ''
5 | labels: ''
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Is your feature request related to a problem? Please describe.**
11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
12 |
13 | **Describe the solution you'd like**
14 | A clear and concise description of what you want to happen.
15 |
16 | **Describe alternatives you've considered**
17 | A clear and concise description of any alternative solutions or features you've considered.
18 |
19 | **Additional context**
20 | Add any other context or screenshots about the feature request here.
21 |
--------------------------------------------------------------------------------
/.github/workflows/npm-publish.yml:
--------------------------------------------------------------------------------
1 | name: Node.js Package
2 |
3 | on:
4 | push:
5 | branches:
6 | - main
7 |
8 | jobs:
9 | build:
10 | runs-on: ubuntu-latest
11 | steps:
12 | - uses: actions/checkout@v2
13 | - uses: actions/setup-node@v2
14 | with:
15 | node-version: 16
16 | - run: npm install
17 | - run: npm run build
18 |
19 | publish-npm:
20 | needs: build
21 | runs-on: ubuntu-latest
22 | steps:
23 | - uses: actions/checkout@v2
24 | - uses: actions/setup-node@v2
25 | with:
26 | node-version: 16
27 | registry-url: https://registry.npmjs.org/
28 | - run: npm install
29 | - run: npm publish
30 | env:
31 | NODE_AUTH_TOKEN: ${{secrets.NPM_AUTH_TOKEN}}
32 |
--------------------------------------------------------------------------------
/.github/workflows/pull-request.yml:
--------------------------------------------------------------------------------
1 | # This workflow will do a clean install of node dependencies, cache/restore them, build the source code and run tests across different versions of node
2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions
3 |
4 | name: Node.js CI
5 |
6 | on:
7 | pull_request:
8 | branches: [develop]
9 |
10 | jobs:
11 | build:
12 | runs-on: ubuntu-latest
13 |
14 | strategy:
15 | matrix:
16 | node-version: [12.x, 14.x, 16.x]
17 | # See supported Node.js release schedule at https://nodejs.org/en/about/releases/
18 |
19 | steps:
20 | - uses: actions/checkout@v2
21 | - name: Use Node.js ${{ matrix.node-version }}
22 | uses: actions/setup-node@v2
23 | with:
24 | node-version: ${{ matrix.node-version }}
25 | cache: "npm"
26 | - run: npm ci
27 | - run: npm run build
28 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 |
2 | # See https://help.github.com/ignore-files/ for more about ignoring files.
3 |
4 | # dependencies
5 | node_modules
6 |
7 | # builds
8 | build
9 | dist
10 | .rpt2_cache
11 |
12 | # misc
13 | .DS_Store
14 | .env
15 | .env.local
16 | .env.development.local
17 | .env.test.local
18 | .env.production.local
19 |
20 | npm-debug.log*
21 | yarn-debug.log*
22 | yarn-error.log*
23 |
24 | .vercel
25 |
26 | coverage
27 | .dccache
--------------------------------------------------------------------------------
/.husky/pre-commit:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 | . "$(dirname "$0")/_/husky.sh"
3 |
4 | yarn run test:coverage && yarn run make-badges && git add 'README.md'
5 |
--------------------------------------------------------------------------------
/.prettierrc.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | singleQuote: true,
3 | printWidth: 80,
4 | };
5 |
--------------------------------------------------------------------------------
/.versionrc.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | types: [
3 | {type: 'feat', section: 'Features'},
4 | {type: 'fix', section: 'Bug Fixes'},
5 | {type: 'test', section: 'Tests'},
6 | {type: 'docs', section: 'Documentation'},
7 | {type: 'build', section: 'Build System'},
8 | {type: 'perf', section: 'Performance Issues'},
9 | {type: 'style', section: 'Styling'},
10 | {type: 'ci', section: 'Pipelines'},
11 | {type: 'refactor', section: 'Refactors'},
12 | ],
13 | };
14 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Changelog
2 |
3 | All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
4 |
5 | ### [1.2.10](https://github.com/the-bugging/react-use-downloader/compare/v1.2.9...v1.2.10) (2025-03-10)
6 |
7 |
8 | ### Bug Fixes
9 |
10 | * improve error handling in resolver with console logging ([45ef270](https://github.com/the-bugging/react-use-downloader/commit/45ef27044d5e1606f64258454d7e23368527e48e))
11 |
12 |
13 | ### Documentation
14 |
15 | * add nik-webdevelop as a contributor for ideas ([9d57115](https://github.com/the-bugging/react-use-downloader/commit/9d57115c7b3200ba231815e7643120592057c5f3))
16 | * update .all-contributorsrc [skip ci] ([0b98d10](https://github.com/the-bugging/react-use-downloader/commit/0b98d1056323eb299e94fd1fba2f6c0cffacb3d3))
17 | * update README.md [skip ci] ([5e2dc37](https://github.com/the-bugging/react-use-downloader/commit/5e2dc373bc195202cff08f2050886be6031dbf3f))
18 |
19 | ### [1.2.9](https://github.com/the-bugging/react-use-downloader/compare/v1.2.8...v1.2.9) (2025-03-10)
20 |
21 | ### [1.2.8](https://github.com/the-bugging/react-use-downloader/compare/v1.2.6...v1.2.8) (2024-04-17)
22 |
23 |
24 | ### Documentation
25 |
26 | * update .all-contributorsrc [skip ci] ([6ee52a6](https://github.com/the-bugging/react-use-downloader/commit/6ee52a6393f393d3241d68c7c68c491d6f8bfe65))
27 | * update README.md [skip ci] ([7b00739](https://github.com/the-bugging/react-use-downloader/commit/7b00739007fdf78b457bc22ed7d21e5e83a5a9a0))
28 |
29 | ### [1.2.7](https://github.com/the-bugging/react-use-downloader/compare/v1.2.6...v1.2.7) (2024-04-16)
30 |
31 | ### [1.2.6](https://github.com/the-bugging/react-use-downloader/compare/v1.2.5...v1.2.6) (2024-04-09)
32 |
33 |
34 | ### Documentation
35 |
36 | * update .all-contributorsrc [skip ci] ([795998a](https://github.com/the-bugging/react-use-downloader/commit/795998a25771dfe99707e62c3b4c71d8d7cc069d))
37 | * update .all-contributorsrc [skip ci] ([2cf94e5](https://github.com/the-bugging/react-use-downloader/commit/2cf94e576331684674e9d6b1f253f08b0ffac30e))
38 | * update README.md [skip ci] ([bde35c2](https://github.com/the-bugging/react-use-downloader/commit/bde35c20e122ed3e37eac8de4049314922500259))
39 | * update README.md [skip ci] ([95e9a75](https://github.com/the-bugging/react-use-downloader/commit/95e9a75a8cc5b830d1339cdfc25f07e7ce6fb40f))
40 |
41 | ### [1.2.5](https://github.com/the-bugging/react-use-downloader/compare/v1.2.3...v1.2.5) (2024-02-17)
42 |
43 |
44 | ### Documentation
45 |
46 | * update .all-contributorsrc [skip ci] ([9ef1cd0](https://github.com/the-bugging/react-use-downloader/commit/9ef1cd0fef5fdb1aea7b500e663461a80842a7d8))
47 | * update .all-contributorsrc [skip ci] ([fe24d4a](https://github.com/the-bugging/react-use-downloader/commit/fe24d4a5dcae06088b4ef5150c5e7c614cf03745))
48 | * update README.md [skip ci] ([a3e3957](https://github.com/the-bugging/react-use-downloader/commit/a3e3957651810a79a190718a495999b2dd3c84ab))
49 | * update README.md [skip ci] ([c5b3ade](https://github.com/the-bugging/react-use-downloader/commit/c5b3ade40b74f4d7f598a0de5252f33ff035fad2))
50 | * upgrade docs ([dac6bf8](https://github.com/the-bugging/react-use-downloader/commit/dac6bf8d952b76ad3485b929404a7875707ab66b))
51 |
52 | ### [1.2.4](https://github.com/the-bugging/react-use-downloader/compare/v1.2.3...v1.2.4) (2023-02-27)
53 |
54 | ### [1.2.3](https://github.com/the-bugging/react-use-downloader/compare/v1.2.2...v1.2.3) (2023-02-25)
55 |
56 |
57 | ### Tests
58 |
59 | * **project:** adjust testing file ([abed1a7](https://github.com/the-bugging/react-use-downloader/commit/abed1a706a41b416994fea9513aeca010e793398))
60 |
61 | ### [1.2.2](https://github.com/the-bugging/react-use-downloader/compare/v1.2.1...v1.2.2) (2023-01-29)
62 |
63 | ### Refactors
64 |
65 | - **project:** adjust interface naming and other things ([077fc88](https://github.com/the-bugging/react-use-downloader/commit/077fc885dfda8371613d45f3754a553950ef1b5b))
66 |
67 | ### [1.2.1](https://github.com/the-bugging/react-use-downloader/compare/v1.2.0...v1.2.1) (2022-11-17)
68 |
69 | ### Bug Fixes
70 |
71 | - upgrade @material-ui/core from 4.12.3 to 4.12.4 ([0ae2aa9](https://github.com/the-bugging/react-use-downloader/commit/0ae2aa9d537291c6d44049ad369ffdc9c2de2399))
72 |
73 | ### Documentation
74 |
75 | - update .all-contributorsrc [skip ci] ([f5f6244](https://github.com/the-bugging/react-use-downloader/commit/f5f6244b2436167a24f59cfa81aaf8d7e661b1c0))
76 | - update .all-contributorsrc [skip ci] ([bac9990](https://github.com/the-bugging/react-use-downloader/commit/bac9990cbecb5ec41daab25f7de20daf2bca0b6f))
77 | - update README.md [skip ci] ([ee870fe](https://github.com/the-bugging/react-use-downloader/commit/ee870fe70153454eb5039dbfb289282263f0c2ec))
78 | - update README.md [skip ci] ([0cbe77f](https://github.com/the-bugging/react-use-downloader/commit/0cbe77f12a3a62855deccb6522f274daee5c74a3))
79 |
80 | ## [1.2.0](https://github.com/the-bugging/react-use-downloader/compare/v1.1.7...v1.2.0) (2022-10-07)
81 |
82 | ### Features
83 |
84 | - **project:** add timeout option ([7a0027a](https://github.com/the-bugging/react-use-downloader/commit/7a0027a58d4c2774f6c3ba8bcce39db721be8371))
85 |
86 | ### Documentation
87 |
88 | - adjust readme ([a68aa9f](https://github.com/the-bugging/react-use-downloader/commit/a68aa9f18a2756703e4a22c180c4bf0758a77a7b))
89 | - create .all-contributorsrc [skip ci] ([a9c17a0](https://github.com/the-bugging/react-use-downloader/commit/a9c17a087c274ac0f3a2c8950c30030ba911f7b9))
90 | - update README.md [skip ci] ([d6cf022](https://github.com/the-bugging/react-use-downloader/commit/d6cf0222a7995a07e9e0545ad528bc88b6469a53))
91 |
92 | ### [1.1.7](https://github.com/the-bugging/react-use-downloader/compare/v1.1.6...v1.1.7) (2022-01-26)
93 |
94 | ### Bug Fixes
95 |
96 | - upgrade @material-ui/core from 4.12.1 to 4.12.2 ([1d15d6b](https://github.com/the-bugging/react-use-downloader/commit/1d15d6ba80ec216195b627d60d0a22728a9e6bbe))
97 | - upgrade @material-ui/core from 4.12.2 to 4.12.3 ([4f2add6](https://github.com/the-bugging/react-use-downloader/commit/4f2add6958aa9b48f33901a2fd28295df63eb1e0))
98 |
99 | ### [1.1.6](https://github.com/the-bugging/react-use-downloader/compare/v1.1.4...v1.1.6) (2021-08-11)
100 |
101 | ### Documentation
102 |
103 | - **ghPages:** update gh pages markdown ([c5e7a77](https://github.com/the-bugging/react-use-downloader/commit/c5e7a77d138d0a05b972cf698637e65b7203ebe4))
104 | - **project:** add example project ([a60a7b4](https://github.com/the-bugging/react-use-downloader/commit/a60a7b4ba8ee80b4bf6a6fe9ef8e214cb87a12ff))
105 |
106 | ### Tests
107 |
108 | - add more testing ([19285dd](https://github.com/the-bugging/react-use-downloader/commit/19285dd1a20c1b4c0443a129a9be4464044a6b12))
109 | - adjust test project ([66d6095](https://github.com/the-bugging/react-use-downloader/commit/66d60953ced492adb64fe3b63d349a8958116483))
110 | - adjust testing ([d8a640c](https://github.com/the-bugging/react-use-downloader/commit/d8a640cf854fae08fd1bcb40784501ac4ce231bf))
111 |
112 | ### [1.1.5](https://github.com/the-bugging/react-use-downloader/compare/v1.1.4...v1.1.5) (2021-03-13)
113 |
114 | ### Documentation
115 |
116 | - **ghPages:** update gh pages markdown ([c5e7a77](https://github.com/the-bugging/react-use-downloader/commit/c5e7a77d138d0a05b972cf698637e65b7203ebe4))
117 | - **project:** add example project ([a60a7b4](https://github.com/the-bugging/react-use-downloader/commit/a60a7b4ba8ee80b4bf6a6fe9ef8e214cb87a12ff))
118 |
119 | ### [1.1.4](https://github.com/the-bugging/react-use-downloader/compare/v1.1.3...v1.1.4) (2021-03-08)
120 |
121 | ### Documentation
122 |
123 | - **ghPages:** update gh pages markdown ([be92888](https://github.com/the-bugging/react-use-downloader/commit/be92888a91f9134b412c12c6cdff9fc259ef1b43))
124 | - **readme:** update readme ([8d39593](https://github.com/the-bugging/react-use-downloader/commit/8d39593c5a57dfdd0e88842b2cef41a05b8f7d00))
125 |
126 | ### Refactors
127 |
128 | - **project:** add tests and other things ([dfa0152](https://github.com/the-bugging/react-use-downloader/commit/dfa01527e7e676adf91d30a2d0724c49d4a3b6e0))
129 |
130 | ### [1.1.3](https://github.com/the-bugging/react-use-downloader/compare/v1.1.2...v1.1.3) (2021-02-22)
131 |
132 | ### [1.1.2](https://github.com/the-bugging/react-use-downloader/compare/v1.1.1...v1.1.2) (2021-02-22)
133 |
134 | ### [1.1.1](https://github.com/the-bugging/react-use-downloader/compare/v1.1.0...v1.1.1) (2021-02-22)
135 |
136 | ### Bug Fixes
137 |
138 | - **project:** fix cancel and download progress ([27b82e5](https://github.com/the-bugging/react-use-downloader/commit/27b82e595fb106270925c033f1dd44a3737e9f99))
139 |
140 | ## [1.1.0](https://github.com/the-bugging/react-use-downloader/compare/v1.0.2...v1.1.0) (2021-02-22)
141 |
142 | ### Features
143 |
144 | - **project:** add isInProgress and cancel ability ([624a09c](https://github.com/the-bugging/react-use-downloader/commit/624a09c28d5071e44164a97657cd86ab9e4140c8))
145 |
146 | ### [1.0.2](https://github.com/the-bugging/react-use-downloader/compare/v1.0.1...v1.0.2) (2021-02-21)
147 |
148 | ### Bug Fixes
149 |
150 | - **progress:** return number instead of string ([74d8481](https://github.com/the-bugging/react-use-downloader/commit/74d8481ed41f59d0bffb0865c37ddcd9e7d9c024))
151 |
152 | ### [1.0.1](https://github.com/the-bugging/react-use-downloader/compare/v1.0.0...v1.0.1) (2021-02-21)
153 |
154 | ## 1.0.0 (2021-02-21)
155 |
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Contributor Covenant Code of Conduct
2 |
3 | ## Our Pledge
4 |
5 | We as members, contributors, and leaders pledge to make participation in our
6 | community a harassment-free experience for everyone, regardless of age, body
7 | size, visible or invisible disability, ethnicity, sex characteristics, gender
8 | identity and expression, level of experience, education, socio-economic status,
9 | nationality, personal appearance, race, religion, or sexual identity
10 | and orientation.
11 |
12 | We pledge to act and interact in ways that contribute to an open, welcoming,
13 | diverse, inclusive, and healthy community.
14 |
15 | ## Our Standards
16 |
17 | Examples of behavior that contributes to a positive environment for our
18 | community include:
19 |
20 | - Demonstrating empathy and kindness toward other people
21 | - Being respectful of differing opinions, viewpoints, and experiences
22 | - Giving and gracefully accepting constructive feedback
23 | - Accepting responsibility and apologizing to those affected by our mistakes,
24 | and learning from the experience
25 | - Focusing on what is best not just for us as individuals, but for the
26 | overall community
27 |
28 | Examples of unacceptable behavior include:
29 |
30 | - The use of sexualized language or imagery, and sexual attention or
31 | advances of any kind
32 | - Trolling, insulting or derogatory comments, and personal or political attacks
33 | - Public or private harassment
34 | - Publishing others' private information, such as a physical or email
35 | address, without their explicit permission
36 | - Other conduct which could reasonably be considered inappropriate in a
37 | professional setting
38 |
39 | ## Enforcement Responsibilities
40 |
41 | Community leaders are responsible for clarifying and enforcing our standards of
42 | acceptable behavior and will take appropriate and fair corrective action in
43 | response to any behavior that they deem inappropriate, threatening, offensive,
44 | or harmful.
45 |
46 | Community leaders have the right and responsibility to remove, edit, or reject
47 | comments, commits, code, wiki edits, issues, and other contributions that are
48 | not aligned to this Code of Conduct, and will communicate reasons for moderation
49 | decisions when appropriate.
50 |
51 | ## Scope
52 |
53 | This Code of Conduct applies within all community spaces, and also applies when
54 | an individual is officially representing the community in public spaces.
55 | Examples of representing our community include using an official e-mail address,
56 | posting via an official social media account, or acting as an appointed
57 | representative at an online or offline event.
58 |
59 | ## Enforcement
60 |
61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be
62 | reported to the community leaders responsible for enforcement at
63 | contact at thebugging dot com.
64 | All complaints will be reviewed and investigated promptly and fairly.
65 |
66 | All community leaders are obligated to respect the privacy and security of the
67 | reporter of any incident.
68 |
69 | ## Enforcement Guidelines
70 |
71 | Community leaders will follow these Community Impact Guidelines in determining
72 | the consequences for any action they deem in violation of this Code of Conduct:
73 |
74 | ### 1. Correction
75 |
76 | **Community Impact**: Use of inappropriate language or other behavior deemed
77 | unprofessional or unwelcome in the community.
78 |
79 | **Consequence**: A private, written warning from community leaders, providing
80 | clarity around the nature of the violation and an explanation of why the
81 | behavior was inappropriate. A public apology may be requested.
82 |
83 | ### 2. Warning
84 |
85 | **Community Impact**: A violation through a single incident or series
86 | of actions.
87 |
88 | **Consequence**: A warning with consequences for continued behavior. No
89 | interaction with the people involved, including unsolicited interaction with
90 | those enforcing the Code of Conduct, for a specified period of time. This
91 | includes avoiding interactions in community spaces as well as external channels
92 | like social media. Violating these terms may lead to a temporary or
93 | permanent ban.
94 |
95 | ### 3. Temporary Ban
96 |
97 | **Community Impact**: A serious violation of community standards, including
98 | sustained inappropriate behavior.
99 |
100 | **Consequence**: A temporary ban from any sort of interaction or public
101 | communication with the community for a specified period of time. No public or
102 | private interaction with the people involved, including unsolicited interaction
103 | with those enforcing the Code of Conduct, is allowed during this period.
104 | Violating these terms may lead to a permanent ban.
105 |
106 | ### 4. Permanent Ban
107 |
108 | **Community Impact**: Demonstrating a pattern of violation of community
109 | standards, including sustained inappropriate behavior, harassment of an
110 | individual, or aggression toward or disparagement of classes of individuals.
111 |
112 | **Consequence**: A permanent ban from any sort of public interaction within
113 | the community.
114 |
115 | ## Attribution
116 |
117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118 | version 2.0, available at
119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
120 |
121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct
122 | enforcement ladder](https://github.com/mozilla/diversity).
123 |
124 | [homepage]: https://www.contributor-covenant.org
125 |
126 | For answers to common questions about this code of conduct, see the FAQ at
127 | https://www.contributor-covenant.org/faq. Translations are available at
128 | https://www.contributor-covenant.org/translations.
129 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | Please do feel free to contribute by opening PRs and/or issues
2 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2021 Olavo Parno
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # react-use-downloader
2 |
3 | > Creates a download handler function with its progress information and cancel ability.
4 |
5 | [](https://www.npmjs.com/package/react-use-downloader)
6 |
7 | ---
8 |
9 | | Statements | Branches | Functions | Lines |
10 | | ----------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- |
11 | |  |  |  |  |
12 |
13 | ## Table of Contents
14 |
15 | - [Running example](#running-example)
16 | - [Install](#install)
17 | - [Usage](#usage)
18 | - [Documentation](#documentation)
19 | - [License](#license)
20 |
21 | ---
22 |
23 | ## Running example
24 |
25 | | Plain |
26 | | --------------------------------------------------------------- |
27 | |  |
28 | | [Preview!](https://codesandbox.io/s/react-use-downloader-0zzoq) |
29 |
30 | ---
31 |
32 | ## Install
33 |
34 | ```bash
35 | npm install --save react-use-downloader
36 | ```
37 |
38 | ---
39 |
40 | ## Usage
41 |
42 | ```jsx
43 | import React from 'react';
44 | import useDownloader from 'react-use-downloader';
45 |
46 | export default function App() {
47 | const { size, elapsed, percentage, download, cancel, error, isInProgress } =
48 | useDownloader();
49 |
50 | const fileUrl =
51 | 'https://upload.wikimedia.org/wikipedia/commons/4/4d/%D0%93%D0%BE%D0%B2%D0%B5%D1%80%D0%BB%D0%B0_%D1%96_%D0%9F%D0%B5%D1%82%D1%80%D0%BE%D1%81_%D0%B2_%D0%BF%D1%80%D0%BE%D0%BC%D1%96%D0%BD%D1%8F%D1%85_%D0%B2%D1%80%D0%B0%D0%BD%D1%96%D1%88%D0%BD%D1%8C%D0%BE%D0%B3%D0%BE_%D1%81%D0%BE%D0%BD%D1%86%D1%8F.jpg';
52 | const filename = 'beautiful-carpathia.jpg';
53 |
54 | return (
55 |
56 |
Download is in {isInProgress ? 'in progress' : 'stopped'}
57 |
download(fileUrl, filename)}>
58 | Click to download the file
59 |
60 |
cancel()}>Cancel the download
61 |
Download size in bytes {size}
62 |
Downloading progress:
63 |
64 |
Elapsed time in seconds {elapsed}
65 | {error &&
possible error {JSON.stringify(error)}
}
66 |
67 | );
68 | }
69 | ```
70 |
71 | ---
72 |
73 | ## Documentation
74 |
75 | `useDownloader()` returns:
76 |
77 | - An object with the following keys:
78 |
79 | | key | description | arguments |
80 | | ------------ | -------------------------------- | ------------------------------------------------------------------------------------------------- |
81 | | size | size in bytes | n/a |
82 | | elapsed | elapsed time in seconds | n/a |
83 | | percentage | percentage in string | n/a |
84 | | download | download function handler | (downloadUrl: string, filename: string, timeout?: number, overrideOptions?: UseDownloaderOptions) |
85 | | cancel | cancel function handler | n/a |
86 | | error | error object from the request | n/a |
87 | | isInProgress | boolean denoting download status | n/a |
88 |
89 | ```jsx
90 | const { size, elapsed, percentage, download, cancel, error, isInProgress } =
91 | useDownloader();
92 | ```
93 |
94 | `useDownloader(options?: UseDownloaderOptions)` also accepts fetch's RequestInit options:
95 |
96 | - Ex.:
97 |
98 | ```jsx
99 | const { download } = useDownloader({
100 | mode: 'no-cors',
101 | credentials: 'include',
102 | headers: {
103 | Authorization: 'Bearer TOKEN',
104 | },
105 | });
106 | ```
107 |
108 | ---
109 |
110 | ## Contributors ✨
111 |
112 | Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):
113 |
114 |
115 |
116 |
117 |
136 |
137 |
138 |
139 |
140 |
141 |
142 | This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!
143 |
144 | ---
145 |
146 | ## License
147 |
148 | react-use-downloader is [MIT licensed](./LICENSE).
149 |
150 | ---
151 |
152 | This hook is created using [create-react-hook](https://github.com/hermanya/create-react-hook).
153 |
--------------------------------------------------------------------------------
/_config.yml:
--------------------------------------------------------------------------------
1 | theme: jekyll-theme-cayman
--------------------------------------------------------------------------------
/assets/readme.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/the-bugging/react-use-downloader/b91977c0dc7c55cf16f287c0844ffba119639bbc/assets/readme.gif
--------------------------------------------------------------------------------
/clean.js:
--------------------------------------------------------------------------------
1 | /* eslint-disable no-unused-vars */
2 | /* eslint-env node */
3 | "use strict";
4 | var fs = require("fs");
5 |
6 | function deleteFolderRecursive(path) {
7 | if (fs.existsSync(path) && fs.lstatSync(path).isDirectory()) {
8 | fs.readdirSync(path).forEach(function (file, index) {
9 | var curPath = path + "/" + file;
10 |
11 | if (fs.lstatSync(curPath).isDirectory()) {
12 | // recurse
13 | deleteFolderRecursive(curPath);
14 | } else {
15 | // delete file
16 | fs.unlinkSync(curPath);
17 | }
18 | });
19 |
20 | console.log(`Deleting directory "${path}"...`);
21 | fs.rmdirSync(path);
22 | }
23 | }
24 |
25 | console.log("Cleaning working tree...");
26 |
27 | process.argv.forEach(function (val, index, array) {
28 | deleteFolderRecursive("./" + val);
29 | });
30 |
31 | console.log("Successfully cleaned working tree!");
32 |
--------------------------------------------------------------------------------
/example/README.md:
--------------------------------------------------------------------------------
1 | This project was bootstrapped with [Create React App](https://github.com/facebookincubator/create-react-app).
2 |
3 | Below you will find some information on how to perform common tasks.
4 | You can find the most recent version of this guide [here](https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md).
5 |
6 | ## Table of Contents
7 |
8 | - [Table of Contents](#table-of-contents)
9 | - [Updating to New Releases](#updating-to-new-releases)
10 | - [Sending Feedback](#sending-feedback)
11 | - [Folder Structure](#folder-structure)
12 | - [Available Scripts](#available-scripts)
13 | - [`npm start`](#npm-start)
14 | - [`npm test`](#npm-test)
15 | - [`npm run build`](#npm-run-build)
16 | - [`npm run eject`](#npm-run-eject)
17 | - [Supported Language Features and Polyfills](#supported-language-features-and-polyfills)
18 | - [Syntax Highlighting in the Editor](#syntax-highlighting-in-the-editor)
19 | - [Displaying Lint Output in the Editor](#displaying-lint-output-in-the-editor)
20 | - [Debugging in the Editor](#debugging-in-the-editor)
21 | - [Visual Studio Code](#visual-studio-code)
22 | - [WebStorm](#webstorm)
23 | - [Formatting Code Automatically](#formatting-code-automatically)
24 | - [Changing the Page ``](#changing-the-page-title)
25 | - [Installing a Dependency](#installing-a-dependency)
26 | - [Importing a Component](#importing-a-component)
27 | - [`Button.js`](#buttonjs)
28 | - [`DangerButton.js`](#dangerbuttonjs)
29 | - [Code Splitting](#code-splitting)
30 | - [`moduleA.js`](#moduleajs)
31 | - [`App.js`](#appjs)
32 | - [With React Router](#with-react-router)
33 | - [Adding a Stylesheet](#adding-a-stylesheet)
34 | - [`Button.css`](#buttoncss)
35 | - [`Button.js`](#buttonjs-1)
36 | - [Using the `public` Folder](#using-the-public-folder)
37 | - [Changing the HTML](#changing-the-html)
38 | - [Adding Assets Outside of the Module System](#adding-assets-outside-of-the-module-system)
39 | - [When to Use the `public` Folder](#when-to-use-the-public-folder)
40 | - [Using Global Variables](#using-global-variables)
41 | - [Adding Bootstrap](#adding-bootstrap)
42 | - [Using a Custom Theme](#using-a-custom-theme)
43 | - [Adding Flow](#adding-flow)
44 | - [Adding Custom Environment Variables](#adding-custom-environment-variables)
45 | - [Referencing Environment Variables in the HTML](#referencing-environment-variables-in-the-html)
46 | - [Adding Temporary Environment Variables In Your Shell](#adding-temporary-environment-variables-in-your-shell)
47 | - [Windows (cmd.exe)](#windows-cmdexe)
48 | - [Linux, macOS (Bash)](#linux-macos-bash)
49 | - [Adding Development Environment Variables In `.env`](#adding-development-environment-variables-in-env)
50 | - [What other `.env` files are can be used?](#what-other-env-files-are-can-be-used)
51 | - [Can I Use Decorators?](#can-i-use-decorators)
52 | - [Integrating with an API Backend](#integrating-with-an-api-backend)
53 | - [Node](#node)
54 | - [Ruby on Rails](#ruby-on-rails)
55 | - [Proxying API Requests in Development](#proxying-api-requests-in-development)
56 | - ["Invalid Host Header" Errors After Configuring Proxy](#%22invalid-host-header%22-errors-after-configuring-proxy)
57 | - [Configuring the Proxy Manually](#configuring-the-proxy-manually)
58 | - [Configuring a WebSocket Proxy](#configuring-a-websocket-proxy)
59 | - [Using HTTPS in Development](#using-https-in-development)
60 | - [Windows (cmd.exe)](#windows-cmdexe-1)
61 | - [Linux, macOS (Bash)](#linux-macos-bash-1)
62 | - [Generating Dynamic ` ` Tags on the Server](#generating-dynamic-meta-tags-on-the-server)
63 | - [Pre-Rendering into Static HTML Files](#pre-rendering-into-static-html-files)
64 | - [Injecting Data from the Server into the Page](#injecting-data-from-the-server-into-the-page)
65 | - [Running Tests](#running-tests)
66 | - [Filename Conventions](#filename-conventions)
67 | - [Command Line Interface](#command-line-interface)
68 | - [Version Control Integration](#version-control-integration)
69 | - [Writing Tests](#writing-tests)
70 | - [Testing Components](#testing-components)
71 | - [Using Third Party Assertion Libraries](#using-third-party-assertion-libraries)
72 | - [Initializing Test Environment](#initializing-test-environment)
73 | - [`src/setupTests.js`](#srcsetuptestsjs)
74 | - [Focusing and Excluding Tests](#focusing-and-excluding-tests)
75 | - [Coverage Reporting](#coverage-reporting)
76 | - [Continuous Integration](#continuous-integration)
77 | - [On CI servers](#on-ci-servers)
78 | - [Travis CI](#travis-ci)
79 | - [CircleCI](#circleci)
80 | - [On your own environment](#on-your-own-environment)
81 | - [Windows (cmd.exe)](#windows-cmdexe-2)
82 | - [Linux, macOS (Bash)](#linux-macos-bash-2)
83 | - [Disabling jsdom](#disabling-jsdom)
84 | - [Snapshot Testing](#snapshot-testing)
85 | - [Editor Integration](#editor-integration)
86 | - [Developing Components in Isolation](#developing-components-in-isolation)
87 | - [Getting Started with Storybook](#getting-started-with-storybook)
88 | - [Getting Started with Styleguidist](#getting-started-with-styleguidist)
89 | - [Making a Progressive Web App](#making-a-progressive-web-app)
90 | - [Opting Out of Caching](#opting-out-of-caching)
91 | - [Offline-First Considerations](#offline-first-considerations)
92 | - [Progressive Web App Metadata](#progressive-web-app-metadata)
93 | - [Analyzing the Bundle Size](#analyzing-the-bundle-size)
94 | - [Deployment](#deployment)
95 | - [Static Server](#static-server)
96 | - [Other Solutions](#other-solutions)
97 | - [Serving Apps with Client-Side Routing](#serving-apps-with-client-side-routing)
98 | - [Building for Relative Paths](#building-for-relative-paths)
99 | - [Serving the Same Build from Different Paths](#serving-the-same-build-from-different-paths)
100 | - [Azure](#azure)
101 | - [Firebase](#firebase)
102 | - [GitHub Pages](#github-pages)
103 | - [Step 1: Add `homepage` to `package.json`](#step-1-add-homepage-to-packagejson)
104 | - [Step 2: Install `gh-pages` and add `deploy` to `scripts` in `package.json`](#step-2-install-gh-pages-and-add-deploy-to-scripts-in-packagejson)
105 | - [Step 3: Deploy the site by running `npm run deploy`](#step-3-deploy-the-site-by-running-npm-run-deploy)
106 | - [Step 4: Ensure your project’s settings use `gh-pages`](#step-4-ensure-your-projects-settings-use-gh-pages)
107 | - [Step 5: Optionally, configure the domain](#step-5-optionally-configure-the-domain)
108 | - [Notes on client-side routing](#notes-on-client-side-routing)
109 | - [Heroku](#heroku)
110 | - [Resolving Heroku Deployment Errors](#resolving-heroku-deployment-errors)
111 | - ["Module not found: Error: Cannot resolve 'file' or 'directory'"](#%22module-not-found-error-cannot-resolve-file-or-directory%22)
112 | - ["Could not find a required file."](#%22could-not-find-a-required-file%22)
113 | - [Netlify](#netlify)
114 | - [Now](#now)
115 | - [S3 and CloudFront](#s3-and-cloudfront)
116 | - [Surge](#surge)
117 | - [Advanced Configuration](#advanced-configuration)
118 | - [Troubleshooting](#troubleshooting)
119 | - [`npm start` doesn’t detect changes](#npm-start-doesnt-detect-changes)
120 | - [`npm test` hangs on macOS Sierra](#npm-test-hangs-on-macos-sierra)
121 | - [`npm run build` exits too early](#npm-run-build-exits-too-early)
122 | - [`npm run build` fails on Heroku](#npm-run-build-fails-on-heroku)
123 | - [Moment.js locales are missing](#momentjs-locales-are-missing)
124 | - [`npm run build` fails to minify](#npm-run-build-fails-to-minify)
125 | - [Something Missing?](#something-missing)
126 |
127 | ## Updating to New Releases
128 |
129 | Create React App is divided into two packages:
130 |
131 | * `create-react-app` is a global command-line utility that you use to create new projects.
132 | * `react-scripts` is a development dependency in the generated projects (including this one).
133 |
134 | You almost never need to update `create-react-app` itself: it delegates all the setup to `react-scripts`.
135 |
136 | When you run `create-react-app`, it always creates the project with the latest version of `react-scripts` so you’ll get all the new features and improvements in newly created apps automatically.
137 |
138 | To update an existing project to a new version of `react-scripts`, [open the changelog](https://github.com/facebookincubator/create-react-app/blob/master/CHANGELOG.md), find the version you’re currently on (check `package.json` in this folder if you’re not sure), and apply the migration instructions for the newer versions.
139 |
140 | In most cases bumping the `react-scripts` version in `package.json` and running `npm install` in this folder should be enough, but it’s good to consult the [changelog](https://github.com/facebookincubator/create-react-app/blob/master/CHANGELOG.md) for potential breaking changes.
141 |
142 | We commit to keeping the breaking changes minimal so you can upgrade `react-scripts` painlessly.
143 |
144 | ## Sending Feedback
145 |
146 | We are always open to [your feedback](https://github.com/facebookincubator/create-react-app/issues).
147 |
148 | ## Folder Structure
149 |
150 | After creation, your project should look like this:
151 |
152 | ```
153 | my-app/
154 | README.md
155 | node_modules/
156 | package.json
157 | public/
158 | index.html
159 | favicon.ico
160 | src/
161 | App.css
162 | App.js
163 | App.test.js
164 | index.css
165 | index.js
166 | logo.svg
167 | ```
168 |
169 | For the project to build, **these files must exist with exact filenames**:
170 |
171 | * `public/index.html` is the page template;
172 | * `src/index.js` is the JavaScript entry point.
173 |
174 | You can delete or rename the other files.
175 |
176 | You may create subdirectories inside `src`. For faster rebuilds, only files inside `src` are processed by Webpack.
177 | You need to **put any JS and CSS files inside `src`**, otherwise Webpack won’t see them.
178 |
179 | Only files inside `public` can be used from `public/index.html`.
180 | Read instructions below for using assets from JavaScript and HTML.
181 |
182 | You can, however, create more top-level directories.
183 | They will not be included in the production build so you can use them for things like documentation.
184 |
185 | ## Available Scripts
186 |
187 | In the project directory, you can run:
188 |
189 | ### `npm start`
190 |
191 | Runs the app in the development mode.
192 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
193 |
194 | The page will reload if you make edits.
195 | You will also see any lint errors in the console.
196 |
197 | ### `npm test`
198 |
199 | Launches the test runner in the interactive watch mode.
200 | See the section about [running tests](#running-tests) for more information.
201 |
202 | ### `npm run build`
203 |
204 | Builds the app for production to the `build` folder.
205 | It correctly bundles React in production mode and optimizes the build for the best performance.
206 |
207 | The build is minified and the filenames include the hashes.
208 | Your app is ready to be deployed!
209 |
210 | See the section about [deployment](#deployment) for more information.
211 |
212 | ### `npm run eject`
213 |
214 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!**
215 |
216 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
217 |
218 | Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
219 |
220 | 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.
221 |
222 | ## Supported Language Features and Polyfills
223 |
224 | This project supports a superset of the latest JavaScript standard.
225 | In addition to [ES6](https://github.com/lukehoban/es6features) syntax features, it also supports:
226 |
227 | * [Exponentiation Operator](https://github.com/rwaldron/exponentiation-operator) (ES2016).
228 | * [Async/await](https://github.com/tc39/ecmascript-asyncawait) (ES2017).
229 | * [Object Rest/Spread Properties](https://github.com/sebmarkbage/ecmascript-rest-spread) (stage 3 proposal).
230 | * [Dynamic import()](https://github.com/tc39/proposal-dynamic-import) (stage 3 proposal)
231 | * [Class Fields and Static Properties](https://github.com/tc39/proposal-class-public-fields) (stage 2 proposal).
232 | * [JSX](https://facebook.github.io/react/docs/introducing-jsx.html) and [Flow](https://flowtype.org/) syntax.
233 |
234 | Learn more about [different proposal stages](https://babeljs.io/docs/plugins/#presets-stage-x-experimental-presets-).
235 |
236 | While we recommend to use experimental proposals with some caution, Facebook heavily uses these features in the product code, so we intend to provide [codemods](https://medium.com/@cpojer/effective-javascript-codemods-5a6686bb46fb) if any of these proposals change in the future.
237 |
238 | Note that **the project only includes a few ES6 [polyfills](https://en.wikipedia.org/wiki/Polyfill)**:
239 |
240 | * [`Object.assign()`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) via [`object-assign`](https://github.com/sindresorhus/object-assign).
241 | * [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) via [`promise`](https://github.com/then/promise).
242 | * [`fetch()`](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) via [`whatwg-fetch`](https://github.com/github/fetch).
243 |
244 | If you use any other ES6+ features that need **runtime support** (such as `Array.from()` or `Symbol`), make sure you are including the appropriate polyfills manually, or that the browsers you are targeting already support them.
245 |
246 | ## Syntax Highlighting in the Editor
247 |
248 | To configure the syntax highlighting in your favorite text editor, head to the [relevant Babel documentation page](https://babeljs.io/docs/editors) and follow the instructions. Some of the most popular editors are covered.
249 |
250 | ## Displaying Lint Output in the Editor
251 |
252 | >Note: this feature is available with `react-scripts@0.2.0` and higher.
253 | >It also only works with npm 3 or higher.
254 |
255 | Some editors, including Sublime Text, Atom, and Visual Studio Code, provide plugins for ESLint.
256 |
257 | They are not required for linting. You should see the linter output right in your terminal as well as the browser console. However, if you prefer the lint results to appear right in your editor, there are some extra steps you can do.
258 |
259 | You would need to install an ESLint plugin for your editor first. Then, add a file called `.eslintrc` to the project root:
260 |
261 | ```js
262 | {
263 | "extends": "react-app"
264 | }
265 | ```
266 |
267 | Now your editor should report the linting warnings.
268 |
269 | Note that even if you edit your `.eslintrc` file further, these changes will **only affect the editor integration**. They won’t affect the terminal and in-browser lint output. This is because Create React App intentionally provides a minimal set of rules that find common mistakes.
270 |
271 | If you want to enforce a coding style for your project, consider using [Prettier](https://github.com/jlongster/prettier) instead of ESLint style rules.
272 |
273 | ## Debugging in the Editor
274 |
275 | **This feature is currently only supported by [Visual Studio Code](https://code.visualstudio.com) and [WebStorm](https://www.jetbrains.com/webstorm/).**
276 |
277 | Visual Studio Code and WebStorm support debugging out of the box with Create React App. This enables you as a developer to write and debug your React code without leaving the editor, and most importantly it enables you to have a continuous development workflow, where context switching is minimal, as you don’t have to switch between tools.
278 |
279 | ### Visual Studio Code
280 |
281 | You would need to have the latest version of [VS Code](https://code.visualstudio.com) and VS Code [Chrome Debugger Extension](https://marketplace.visualstudio.com/items?itemName=msjsdiag.debugger-for-chrome) installed.
282 |
283 | Then add the block below to your `launch.json` file and put it inside the `.vscode` folder in your app’s root directory.
284 |
285 | ```json
286 | {
287 | "version": "0.2.0",
288 | "configurations": [{
289 | "name": "Chrome",
290 | "type": "chrome",
291 | "request": "launch",
292 | "url": "http://localhost:3000",
293 | "webRoot": "${workspaceRoot}/src",
294 | "userDataDir": "${workspaceRoot}/.vscode/chrome",
295 | "sourceMapPathOverrides": {
296 | "webpack:///src/*": "${webRoot}/*"
297 | }
298 | }]
299 | }
300 | ```
301 | >Note: the URL may be different if you've made adjustments via the [HOST or PORT environment variables](#advanced-configuration).
302 |
303 | Start your app by running `npm start`, and start debugging in VS Code by pressing `F5` or by clicking the green debug icon. You can now write code, set breakpoints, make changes to the code, and debug your newly modified code—all from your editor.
304 |
305 | ### WebStorm
306 |
307 | You would need to have [WebStorm](https://www.jetbrains.com/webstorm/) and [JetBrains IDE Support](https://chrome.google.com/webstore/detail/jetbrains-ide-support/hmhgeddbohgjknpmjagkdomcpobmllji) Chrome extension installed.
308 |
309 | In the WebStorm menu `Run` select `Edit Configurations...`. Then click `+` and select `JavaScript Debug`. Paste `http://localhost:3000` into the URL field and save the configuration.
310 |
311 | >Note: the URL may be different if you've made adjustments via the [HOST or PORT environment variables](#advanced-configuration).
312 |
313 | Start your app by running `npm start`, then press `^D` on macOS or `F9` on Windows and Linux or click the green debug icon to start debugging in WebStorm.
314 |
315 | The same way you can debug your application in IntelliJ IDEA Ultimate, PhpStorm, PyCharm Pro, and RubyMine.
316 |
317 | ## Formatting Code Automatically
318 |
319 | Prettier is an opinionated code formatter with support for JavaScript, CSS and JSON. With Prettier you can format the code you write automatically to ensure a code style within your project. See the [Prettier's GitHub page](https://github.com/prettier/prettier) for more information, and look at this [page to see it in action](https://prettier.github.io/prettier/).
320 |
321 | To format our code whenever we make a commit in git, we need to install the following dependencies:
322 |
323 | ```sh
324 | npm install --save husky lint-staged prettier
325 | ```
326 |
327 | Alternatively you may use `yarn`:
328 |
329 | ```sh
330 | yarn add husky lint-staged prettier
331 | ```
332 |
333 | * `husky` makes it easy to use githooks as if they are npm scripts.
334 | * `lint-staged` allows us to run scripts on staged files in git. See this [blog post about lint-staged to learn more about it](https://medium.com/@okonetchnikov/make-linting-great-again-f3890e1ad6b8).
335 | * `prettier` is the JavaScript formatter we will run before commits.
336 |
337 | Now we can make sure every file is formatted correctly by adding a few lines to the `package.json` in the project root.
338 |
339 | Add the following line to `scripts` section:
340 |
341 | ```diff
342 | "scripts": {
343 | + "precommit": "lint-staged",
344 | "start": "react-scripts start",
345 | "build": "react-scripts build",
346 | ```
347 |
348 | Next we add a 'lint-staged' field to the `package.json`, for example:
349 |
350 | ```diff
351 | "dependencies": {
352 | // ...
353 | },
354 | + "lint-staged": {
355 | + "src/**/*.{js,jsx,json,css}": [
356 | + "prettier --single-quote --write",
357 | + "git add"
358 | + ]
359 | + },
360 | "scripts": {
361 | ```
362 |
363 | Now, whenever you make a commit, Prettier will format the changed files automatically. You can also run `./node_modules/.bin/prettier --single-quote --write "src/**/*.{js,jsx}"` to format your entire project for the first time.
364 |
365 | Next you might want to integrate Prettier in your favorite editor. Read the section on [Editor Integration](https://github.com/prettier/prettier#editor-integration) on the Prettier GitHub page.
366 |
367 | ## Changing the Page ``
368 |
369 | You can find the source HTML file in the `public` folder of the generated project. You may edit the `` tag in it to change the title from “React App” to anything else.
370 |
371 | Note that normally you wouldn’t edit files in the `public` folder very often. For example, [adding a stylesheet](#adding-a-stylesheet) is done without touching the HTML.
372 |
373 | If you need to dynamically update the page title based on the content, you can use the browser [`document.title`](https://developer.mozilla.org/en-US/docs/Web/API/Document/title) API. For more complex scenarios when you want to change the title from React components, you can use [React Helmet](https://github.com/nfl/react-helmet), a third party library.
374 |
375 | If you use a custom server for your app in production and want to modify the title before it gets sent to the browser, you can follow advice in [this section](#generating-dynamic-meta-tags-on-the-server). Alternatively, you can pre-build each page as a static HTML file which then loads the JavaScript bundle, which is covered [here](#pre-rendering-into-static-html-files).
376 |
377 | ## Installing a Dependency
378 |
379 | The generated project includes React and ReactDOM as dependencies. It also includes a set of scripts used by Create React App as a development dependency. You may install other dependencies (for example, React Router) with `npm`:
380 |
381 | ```sh
382 | npm install --save react-router
383 | ```
384 |
385 | Alternatively you may use `yarn`:
386 |
387 | ```sh
388 | yarn add react-router
389 | ```
390 |
391 | This works for any library, not just `react-router`.
392 |
393 | ## Importing a Component
394 |
395 | This project setup supports ES6 modules thanks to Babel.
396 | While you can still use `require()` and `module.exports`, we encourage you to use [`import` and `export`](http://exploringjs.com/es6/ch_modules.html) instead.
397 |
398 | For example:
399 |
400 | ### `Button.js`
401 |
402 | ```js
403 | import React, { Component } from 'react';
404 |
405 | class Button extends Component {
406 | render() {
407 | // ...
408 | }
409 | }
410 |
411 | export default Button; // Don’t forget to use export default!
412 | ```
413 |
414 | ### `DangerButton.js`
415 |
416 |
417 | ```js
418 | import React, { Component } from 'react';
419 | import Button from './Button'; // Import a component from another file
420 |
421 | class DangerButton extends Component {
422 | render() {
423 | return ;
424 | }
425 | }
426 |
427 | export default DangerButton;
428 | ```
429 |
430 | Be aware of the [difference between default and named exports](http://stackoverflow.com/questions/36795819/react-native-es-6-when-should-i-use-curly-braces-for-import/36796281#36796281). It is a common source of mistakes.
431 |
432 | We suggest that you stick to using default imports and exports when a module only exports a single thing (for example, a component). That’s what you get when you use `export default Button` and `import Button from './Button'`.
433 |
434 | Named exports are useful for utility modules that export several functions. A module may have at most one default export and as many named exports as you like.
435 |
436 | Learn more about ES6 modules:
437 |
438 | * [When to use the curly braces?](http://stackoverflow.com/questions/36795819/react-native-es-6-when-should-i-use-curly-braces-for-import/36796281#36796281)
439 | * [Exploring ES6: Modules](http://exploringjs.com/es6/ch_modules.html)
440 | * [Understanding ES6: Modules](https://leanpub.com/understandinges6/read#leanpub-auto-encapsulating-code-with-modules)
441 |
442 | ## Code Splitting
443 |
444 | Instead of downloading the entire app before users can use it, code splitting allows you to split your code into small chunks which you can then load on demand.
445 |
446 | This project setup supports code splitting via [dynamic `import()`](http://2ality.com/2017/01/import-operator.html#loading-code-on-demand). Its [proposal](https://github.com/tc39/proposal-dynamic-import) is in stage 3. The `import()` function-like form takes the module name as an argument and returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) which always resolves to the namespace object of the module.
447 |
448 | Here is an example:
449 |
450 | ### `moduleA.js`
451 |
452 | ```js
453 | const moduleA = 'Hello';
454 |
455 | export { moduleA };
456 | ```
457 | ### `App.js`
458 |
459 | ```js
460 | import React, { Component } from 'react';
461 |
462 | class App extends Component {
463 | handleClick = () => {
464 | import('./moduleA')
465 | .then(({ moduleA }) => {
466 | // Use moduleA
467 | })
468 | .catch(err => {
469 | // Handle failure
470 | });
471 | };
472 |
473 | render() {
474 | return (
475 |
476 | Load
477 |
478 | );
479 | }
480 | }
481 |
482 | export default App;
483 | ```
484 |
485 | This will make `moduleA.js` and all its unique dependencies as a separate chunk that only loads after the user clicks the 'Load' button.
486 |
487 | You can also use it with `async` / `await` syntax if you prefer it.
488 |
489 | ### With React Router
490 |
491 | If you are using React Router check out [this tutorial](http://serverless-stack.com/chapters/code-splitting-in-create-react-app.html) on how to use code splitting with it. You can find the companion GitHub repository [here](https://github.com/AnomalyInnovations/serverless-stack-demo-client/tree/code-splitting-in-create-react-app).
492 |
493 | ## Adding a Stylesheet
494 |
495 | This project setup uses [Webpack](https://webpack.js.org/) for handling all assets. Webpack offers a custom way of “extending” the concept of `import` beyond JavaScript. To express that a JavaScript file depends on a CSS file, you need to **import the CSS from the JavaScript file**:
496 |
497 | ### `Button.css`
498 |
499 | ```css
500 | .Button {
501 | padding: 20px;
502 | }
503 | ```
504 |
505 | ### `Button.js`
506 |
507 | ```js
508 | import React, { Component } from 'react';
509 | import './Button.css'; // Tell Webpack that Button.js uses these styles
510 |
511 | class Button extends Component {
512 | render() {
513 | // You can use them as regular CSS styles
514 | return
;
515 | }
516 | }
517 | ```
518 |
519 | **This is not required for React** but many people find this feature convenient. You can read about the benefits of this approach [here](https://medium.com/seek-ui-engineering/block-element-modifying-your-javascript-components-d7f99fcab52b). However you should be aware that this makes your code less portable to other build tools and environments than Webpack.
520 |
521 | In development, expressing dependencies this way allows your styles to be reloaded on the fly as you edit them. In production, all CSS files will be concatenated into a single minified `.css` file in the build output.
522 |
523 | If you are concerned about using Webpack-specific semantics, you can put all your CSS right into `src/index.css`. It would still be imported from `src/index.js`, but you could always remove that import if you later migrate to a different build tool.
524 |
525 | ## Using the `public` Folder
526 |
527 | >Note: this feature is available with `react-scripts@0.5.0` and higher.
528 |
529 | ### Changing the HTML
530 |
531 | The `public` folder contains the HTML file so you can tweak it, for example, to [set the page title](#changing-the-page-title).
532 | The `
1040 | ```
1041 |
1042 | 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.**
1043 |
1044 | ## Running Tests
1045 |
1046 | >Note: this feature is available with `react-scripts@0.3.0` and higher.
1047 | >[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)
1048 |
1049 | 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.
1050 |
1051 | 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.
1052 |
1053 | 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.
1054 |
1055 | 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.
1056 |
1057 | ### Filename Conventions
1058 |
1059 | Jest will look for test files with any of the following popular naming conventions:
1060 |
1061 | * Files with `.js` suffix in `__tests__` folders.
1062 | * Files with `.test.js` suffix.
1063 | * Files with `.spec.js` suffix.
1064 |
1065 | The `.test.js` / `.spec.js` files (or the `__tests__` folders) can be located at any depth under the `src` top level folder.
1066 |
1067 | 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.
1068 |
1069 | ### Command Line Interface
1070 |
1071 | 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.
1072 |
1073 | 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:
1074 |
1075 | 
1076 |
1077 | ### Version Control Integration
1078 |
1079 | 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.
1080 |
1081 | 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.
1082 |
1083 | 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.
1084 |
1085 | ### Writing Tests
1086 |
1087 | 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.
1088 |
1089 | Jest provides a built-in `expect()` global function for making assertions. A basic test could look like this:
1090 |
1091 | ```js
1092 | import sum from './sum';
1093 |
1094 | it('sums numbers', () => {
1095 | expect(sum(1, 2)).toEqual(3);
1096 | expect(sum(2, 2)).toEqual(4);
1097 | });
1098 | ```
1099 |
1100 | All `expect()` matchers supported by Jest are [extensively documented here](http://facebook.github.io/jest/docs/expect.html).
1101 | 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.
1102 |
1103 | ### Testing Components
1104 |
1105 | 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.
1106 |
1107 | 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:
1108 |
1109 | ```js
1110 | import React from 'react';
1111 | import ReactDOM from 'react-dom';
1112 | import App from './App';
1113 |
1114 | it('renders without crashing', () => {
1115 | const div = document.createElement('div');
1116 | ReactDOM.render( , div);
1117 | });
1118 | ```
1119 |
1120 | This test mounts a component and makes sure that it didn’t throw during rendering. Tests like this provide a lot 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.js`.
1121 |
1122 | 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.
1123 |
1124 | 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:
1125 |
1126 | ```sh
1127 | npm install --save enzyme react-test-renderer
1128 | ```
1129 |
1130 | Alternatively you may use `yarn`:
1131 |
1132 | ```sh
1133 | yarn add enzyme react-test-renderer
1134 | ```
1135 |
1136 | You can write a smoke test with it too:
1137 |
1138 | ```js
1139 | import React from 'react';
1140 | import { shallow } from 'enzyme';
1141 | import App from './App';
1142 |
1143 | it('renders without crashing', () => {
1144 | shallow( );
1145 | });
1146 | ```
1147 |
1148 | Unlike the previous smoke test using `ReactDOM.render()`, this test only renders `` and doesn’t go deeper. For example, even if `` itself renders a `` that throws, this test will pass. Shallow rendering is great for isolated unit tests, but you may still want to create some full rendering tests to ensure the components integrate correctly. Enzyme supports [full rendering with `mount()`](http://airbnb.io/enzyme/docs/api/mount.html), and you can also use it for testing state changes and component lifecycle.
1149 |
1150 | You can read the [Enzyme documentation](http://airbnb.io/enzyme/) for more testing techniques. Enzyme documentation uses Chai and Sinon for assertions but you don’t have to use them because Jest provides built-in `expect()` and `jest.fn()` for spies.
1151 |
1152 | Here is an example from Enzyme documentation that asserts specific output, rewritten to use Jest matchers:
1153 |
1154 | ```js
1155 | import React from 'react';
1156 | import { shallow } from 'enzyme';
1157 | import App from './App';
1158 |
1159 | it('renders welcome message', () => {
1160 | const wrapper = shallow( );
1161 | const welcome = Welcome to React ;
1162 | // expect(wrapper.contains(welcome)).to.equal(true);
1163 | expect(wrapper.contains(welcome)).toEqual(true);
1164 | });
1165 | ```
1166 |
1167 | All Jest matchers are [extensively documented here](http://facebook.github.io/jest/docs/expect.html).
1168 | Nevertheless you can use a third-party assertion library like [Chai](http://chaijs.com/) if you want to, as described below.
1169 |
1170 | Additionally, you might find [jest-enzyme](https://github.com/blainekasten/enzyme-matchers) helpful to simplify your tests with readable matchers. The above `contains` code can be written simpler with jest-enzyme.
1171 |
1172 | ```js
1173 | expect(wrapper).toContainReact(welcome)
1174 | ```
1175 |
1176 | To enable this, install `jest-enzyme`:
1177 |
1178 | ```sh
1179 | npm install --save jest-enzyme
1180 | ```
1181 |
1182 | Alternatively you may use `yarn`:
1183 |
1184 | ```sh
1185 | yarn add jest-enzyme
1186 | ```
1187 |
1188 | Import it in [`src/setupTests.js`](#initializing-test-environment) to make its matchers available in every test:
1189 |
1190 | ```js
1191 | import 'jest-enzyme';
1192 | ```
1193 |
1194 | ### Using Third Party Assertion Libraries
1195 |
1196 | We recommend that you use `expect()` for assertions and `jest.fn()` for spies. If you are having issues with them please [file those against Jest](https://github.com/facebook/jest/issues/new), and we’ll fix them. We intend to keep making them better for React, supporting, for example, [pretty-printing React elements as JSX](https://github.com/facebook/jest/pull/1566).
1197 |
1198 | However, if you are used to other libraries, such as [Chai](http://chaijs.com/) and [Sinon](http://sinonjs.org/), or if you have existing code using them that you’d like to port over, you can import them normally like this:
1199 |
1200 | ```js
1201 | import sinon from 'sinon';
1202 | import { expect } from 'chai';
1203 | ```
1204 |
1205 | and then use them in your tests like you normally do.
1206 |
1207 | ### Initializing Test Environment
1208 |
1209 | >Note: this feature is available with `react-scripts@0.4.0` and higher.
1210 |
1211 | If your app uses a browser API that you need to mock in your tests or if you just need a global setup before running your tests, add a `src/setupTests.js` to your project. It will be automatically executed before running your tests.
1212 |
1213 | For example:
1214 |
1215 | #### `src/setupTests.js`
1216 | ```js
1217 | const localStorageMock = {
1218 | getItem: jest.fn(),
1219 | setItem: jest.fn(),
1220 | clear: jest.fn()
1221 | };
1222 | global.localStorage = localStorageMock
1223 | ```
1224 |
1225 | ### Focusing and Excluding Tests
1226 |
1227 | You can replace `it()` with `xit()` to temporarily exclude a test from being executed.
1228 | Similarly, `fit()` lets you focus on a specific test without running any other tests.
1229 |
1230 | ### Coverage Reporting
1231 |
1232 | Jest has an integrated coverage reporter that works well with ES6 and requires no configuration.
1233 | Run `npm test -- --coverage` (note extra `--` in the middle) to include a coverage report like this:
1234 |
1235 | 
1236 |
1237 | Note that tests run much slower with coverage so it is recommended to run it separately from your normal workflow.
1238 |
1239 | ### Continuous Integration
1240 |
1241 | By default `npm test` runs the watcher with interactive CLI. However, you can force it to run tests once and finish the process by setting an environment variable called `CI`.
1242 |
1243 | When creating a build of your application with `npm run build` linter warnings are not checked by default. Like `npm test`, you can force the build to perform a linter warning check by setting the environment variable `CI`. If any warnings are encountered then the build fails.
1244 |
1245 | Popular CI servers already set the environment variable `CI` by default but you can do this yourself too:
1246 |
1247 | ### On CI servers
1248 | #### Travis CI
1249 |
1250 | 1. Following the [Travis Getting started](https://docs.travis-ci.com/user/getting-started/) guide for syncing your GitHub repository with Travis. You may need to initialize some settings manually in your [profile](https://travis-ci.org/profile) page.
1251 | 1. Add a `.travis.yml` file to your git repository.
1252 | ```
1253 | language: node_js
1254 | node_js:
1255 | - 6
1256 | cache:
1257 | directories:
1258 | - node_modules
1259 | script:
1260 | - npm run build
1261 | - npm test
1262 | ```
1263 | 1. Trigger your first build with a git push.
1264 | 1. [Customize your Travis CI Build](https://docs.travis-ci.com/user/customizing-the-build/) if needed.
1265 |
1266 | #### CircleCI
1267 |
1268 | Follow [this article](https://medium.com/@knowbody/circleci-and-zeits-now-sh-c9b7eebcd3c1) to set up CircleCI with a Create React App project.
1269 |
1270 | ### On your own environment
1271 | ##### Windows (cmd.exe)
1272 |
1273 | ```cmd
1274 | set CI=true&&npm test
1275 | ```
1276 |
1277 | ```cmd
1278 | set CI=true&&npm run build
1279 | ```
1280 |
1281 | (Note: the lack of whitespace is intentional.)
1282 |
1283 | ##### Linux, macOS (Bash)
1284 |
1285 | ```bash
1286 | CI=true npm test
1287 | ```
1288 |
1289 | ```bash
1290 | CI=true npm run build
1291 | ```
1292 |
1293 | The test command will force Jest to run tests once instead of launching the watcher.
1294 |
1295 | > If you find yourself doing this often in development, please [file an issue](https://github.com/facebookincubator/create-react-app/issues/new) to tell us about your use case because we want to make watcher the best experience and are open to changing how it works to accommodate more workflows.
1296 |
1297 | The build command will check for linter warnings and fail if any are found.
1298 |
1299 | ### Disabling jsdom
1300 |
1301 | By default, the `package.json` of the generated project looks like this:
1302 |
1303 | ```js
1304 | "scripts": {
1305 | "start": "react-scripts start",
1306 | "build": "react-scripts build",
1307 | "test": "react-scripts test --env=jsdom"
1308 | ```
1309 |
1310 | If you know that none of your tests depend on [jsdom](https://github.com/tmpvar/jsdom), you can safely remove `--env=jsdom`, and your tests will run faster:
1311 |
1312 | ```diff
1313 | "scripts": {
1314 | "start": "react-scripts start",
1315 | "build": "react-scripts build",
1316 | - "test": "react-scripts test --env=jsdom"
1317 | + "test": "react-scripts test"
1318 | ```
1319 |
1320 | To help you make up your mind, here is a list of APIs that **need jsdom**:
1321 |
1322 | * Any browser globals like `window` and `document`
1323 | * [`ReactDOM.render()`](https://facebook.github.io/react/docs/top-level-api.html#reactdom.render)
1324 | * [`TestUtils.renderIntoDocument()`](https://facebook.github.io/react/docs/test-utils.html#renderintodocument) ([a shortcut](https://github.com/facebook/react/blob/34761cf9a252964abfaab6faf74d473ad95d1f21/src/test/ReactTestUtils.js#L83-L91) for the above)
1325 | * [`mount()`](http://airbnb.io/enzyme/docs/api/mount.html) in [Enzyme](http://airbnb.io/enzyme/index.html)
1326 |
1327 | In contrast, **jsdom is not needed** for the following APIs:
1328 |
1329 | * [`TestUtils.createRenderer()`](https://facebook.github.io/react/docs/test-utils.html#shallow-rendering) (shallow rendering)
1330 | * [`shallow()`](http://airbnb.io/enzyme/docs/api/shallow.html) in [Enzyme](http://airbnb.io/enzyme/index.html)
1331 |
1332 | Finally, jsdom is also not needed for [snapshot testing](http://facebook.github.io/jest/blog/2016/07/27/jest-14.html).
1333 |
1334 | ### Snapshot Testing
1335 |
1336 | Snapshot testing is a feature of Jest that automatically generates text snapshots of your components and saves them on the disk so if the UI output changes, you get notified without manually writing any assertions on the component output. [Read more about snapshot testing.](http://facebook.github.io/jest/blog/2016/07/27/jest-14.html)
1337 |
1338 | ### Editor Integration
1339 |
1340 | If you use [Visual Studio Code](https://code.visualstudio.com), there is a [Jest extension](https://github.com/orta/vscode-jest) which works with Create React App out of the box. This provides a lot of IDE-like features while using a text editor: showing the status of a test run with potential fail messages inline, starting and stopping the watcher automatically, and offering one-click snapshot updates.
1341 |
1342 | 
1343 |
1344 | ## Developing Components in Isolation
1345 |
1346 | Usually, in an app, you have a lot of UI components, and each of them has many different states.
1347 | For an example, a simple button component could have following states:
1348 |
1349 | * In a regular state, with a text label.
1350 | * In the disabled mode.
1351 | * In a loading state.
1352 |
1353 | Usually, it’s hard to see these states without running a sample app or some examples.
1354 |
1355 | Create React App doesn’t include any tools for this by default, but you can easily add [Storybook for React](https://storybook.js.org) ([source](https://github.com/storybooks/storybook)) or [React Styleguidist](https://react-styleguidist.js.org/) ([source](https://github.com/styleguidist/react-styleguidist)) to your project. **These are third-party tools that let you develop components and see all their states in isolation from your app**.
1356 |
1357 | 
1358 |
1359 | You can also deploy your Storybook or style guide as a static app. This way, everyone in your team can view and review different states of UI components without starting a backend server or creating an account in your app.
1360 |
1361 | ### Getting Started with Storybook
1362 |
1363 | Storybook is a development environment for React UI components. It allows you to browse a component library, view the different states of each component, and interactively develop and test components.
1364 |
1365 | First, install the following npm package globally:
1366 |
1367 | ```sh
1368 | npm install -g @storybook/cli
1369 | ```
1370 |
1371 | Then, run the following command inside your app’s directory:
1372 |
1373 | ```sh
1374 | getstorybook
1375 | ```
1376 |
1377 | After that, follow the instructions on the screen.
1378 |
1379 | Learn more about React Storybook:
1380 |
1381 | * Screencast: [Getting Started with React Storybook](https://egghead.io/lessons/react-getting-started-with-react-storybook)
1382 | * [GitHub Repo](https://github.com/storybooks/storybook)
1383 | * [Documentation](https://storybook.js.org/basics/introduction/)
1384 | * [Snapshot Testing UI](https://github.com/storybooks/storybook/tree/master/addons/storyshots) with Storybook + addon/storyshot
1385 |
1386 | ### Getting Started with Styleguidist
1387 |
1388 | Styleguidist combines a style guide, where all your components are presented on a single page with their props documentation and usage examples, with an environment for developing components in isolation, similar to Storybook. In Styleguidist you write examples in Markdown, where each code snippet is rendered as a live editable playground.
1389 |
1390 | First, install Styleguidist:
1391 |
1392 | ```sh
1393 | npm install --save react-styleguidist
1394 | ```
1395 |
1396 | Alternatively you may use `yarn`:
1397 |
1398 | ```sh
1399 | yarn add react-styleguidist
1400 | ```
1401 |
1402 | Then, add these scripts to your `package.json`:
1403 |
1404 | ```diff
1405 | "scripts": {
1406 | + "styleguide": "styleguidist server",
1407 | + "styleguide:build": "styleguidist build",
1408 | "start": "react-scripts start",
1409 | ```
1410 |
1411 | Then, run the following command inside your app’s directory:
1412 |
1413 | ```sh
1414 | npm run styleguide
1415 | ```
1416 |
1417 | After that, follow the instructions on the screen.
1418 |
1419 | Learn more about React Styleguidist:
1420 |
1421 | * [GitHub Repo](https://github.com/styleguidist/react-styleguidist)
1422 | * [Documentation](https://react-styleguidist.js.org/docs/getting-started.html)
1423 |
1424 | ## Making a Progressive Web App
1425 |
1426 | By default, the production build is a fully functional, offline-first
1427 | [Progressive Web App](https://developers.google.com/web/progressive-web-apps/).
1428 |
1429 | Progressive Web Apps are faster and more reliable than traditional web pages, and provide an engaging mobile experience:
1430 |
1431 | * All static site assets are cached so that your page loads fast on subsequent visits, regardless of network connectivity (such as 2G or 3G). Updates are downloaded in the background.
1432 | * Your app will work regardless of network state, even if offline. This means your users will be able to use your app at 10,000 feet and on the Subway.
1433 | * On mobile devices, your app can be added directly to the user's home screen, app icon and all. You can also re-engage users using web **push notifications**. This eliminates the need for the app store.
1434 |
1435 | The [`sw-precache-webpack-plugin`](https://github.com/goldhand/sw-precache-webpack-plugin)
1436 | is integrated into production configuration,
1437 | and it will take care of generating a service worker file that will automatically
1438 | precache all of your local assets and keep them up to date as you deploy updates.
1439 | The service worker will use a [cache-first strategy](https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#cache-falling-back-to-network)
1440 | for handling all requests for local assets, including the initial HTML, ensuring
1441 | that your web app is reliably fast, even on a slow or unreliable network.
1442 |
1443 | ### Opting Out of Caching
1444 |
1445 | If you would prefer not to enable service workers prior to your initial
1446 | production deployment, then remove the call to `serviceWorkerRegistration.register()`
1447 | from [`src/index.js`](src/index.js).
1448 |
1449 | If you had previously enabled service workers in your production deployment and
1450 | have decided that you would like to disable them for all your existing users,
1451 | you can swap out the call to `serviceWorkerRegistration.register()` in
1452 | [`src/index.js`](src/index.js) with a call to `serviceWorkerRegistration.unregister()`.
1453 | After the user visits a page that has `serviceWorkerRegistration.unregister()`,
1454 | the service worker will be uninstalled. Note that depending on how `/service-worker.js` is served,
1455 | it may take up to 24 hours for the cache to be invalidated.
1456 |
1457 | ### Offline-First Considerations
1458 |
1459 | 1. Service workers [require HTTPS](https://developers.google.com/web/fundamentals/getting-started/primers/service-workers#you_need_https),
1460 | although to facilitate local testing, that policy
1461 | [does not apply to `localhost`](http://stackoverflow.com/questions/34160509/options-for-testing-service-workers-via-http/34161385#34161385).
1462 | If your production web server does not support HTTPS, then the service worker
1463 | registration will fail, but the rest of your web app will remain functional.
1464 |
1465 | 1. Service workers are [not currently supported](https://jakearchibald.github.io/isserviceworkerready/)
1466 | in all web browsers. Service worker registration [won't be attempted](src/registerServiceWorker.js)
1467 | on browsers that lack support.
1468 |
1469 | 1. The service worker is only enabled in the [production environment](#deployment),
1470 | e.g. the output of `npm run build`. It's recommended that you do not enable an
1471 | offline-first service worker in a development environment, as it can lead to
1472 | frustration when previously cached assets are used and do not include the latest
1473 | changes you've made locally.
1474 |
1475 | 1. If you *need* to test your offline-first service worker locally, build
1476 | the application (using `npm run build`) and run a simple http server from your
1477 | build directory. After running the build script, `create-react-app` will give
1478 | instructions for one way to test your production build locally and the [deployment instructions](#deployment) have
1479 | instructions for using other methods. *Be sure to always use an
1480 | incognito window to avoid complications with your browser cache.*
1481 |
1482 | 1. If possible, configure your production environment to serve the generated
1483 | `service-worker.js` [with HTTP caching disabled](http://stackoverflow.com/questions/38843970/service-worker-javascript-update-frequency-every-24-hours).
1484 | If that's not possible—[GitHub Pages](#github-pages), for instance, does not
1485 | allow you to change the default 10 minute HTTP cache lifetime—then be aware
1486 | that if you visit your production site, and then revisit again before
1487 | `service-worker.js` has expired from your HTTP cache, you'll continue to get
1488 | the previously cached assets from the service worker. If you have an immediate
1489 | need to view your updated production deployment, performing a shift-refresh
1490 | will temporarily disable the service worker and retrieve all assets from the
1491 | network.
1492 |
1493 | 1. Users aren't always familiar with offline-first web apps. It can be useful to
1494 | [let the user know](https://developers.google.com/web/fundamentals/instant-and-offline/offline-ux#inform_the_user_when_the_app_is_ready_for_offline_consumption)
1495 | when the service worker has finished populating your caches (showing a "This web
1496 | app works offline!" message) and also let them know when the service worker has
1497 | fetched the latest updates that will be available the next time they load the
1498 | page (showing a "New content is available; please refresh." message). Showing
1499 | this messages is currently left as an exercise to the developer, but as a
1500 | starting point, you can make use of the logic included in [`src/registerServiceWorker.js`](src/registerServiceWorker.js), which
1501 | demonstrates which service worker lifecycle events to listen for to detect each
1502 | scenario, and which as a default, just logs appropriate messages to the
1503 | JavaScript console.
1504 |
1505 | 1. By default, the generated service worker file will not intercept or cache any
1506 | cross-origin traffic, like HTTP [API requests](#integrating-with-an-api-backend),
1507 | images, or embeds loaded from a different domain. If you would like to use a
1508 | runtime caching strategy for those requests, you can [`eject`](#npm-run-eject)
1509 | and then configure the
1510 | [`runtimeCaching`](https://github.com/GoogleChrome/sw-precache#runtimecaching-arrayobject)
1511 | option in the `SWPrecacheWebpackPlugin` section of
1512 | [`webpack.config.prod.js`](../config/webpack.config.prod.js).
1513 |
1514 | ### Progressive Web App Metadata
1515 |
1516 | The default configuration includes a web app manifest located at
1517 | [`public/manifest.json`](public/manifest.json), that you can customize with
1518 | details specific to your web application.
1519 |
1520 | When a user adds a web app to their homescreen using Chrome or Firefox on
1521 | Android, the metadata in [`manifest.json`](public/manifest.json) determines what
1522 | icons, names, and branding colors to use when the web app is displayed.
1523 | [The Web App Manifest guide](https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/)
1524 | provides more context about what each field means, and how your customizations
1525 | will affect your users' experience.
1526 |
1527 | ## Analyzing the Bundle Size
1528 |
1529 | [Source map explorer](https://www.npmjs.com/package/source-map-explorer) analyzes
1530 | JavaScript bundles using the source maps. This helps you understand where code
1531 | bloat is coming from.
1532 |
1533 | To add Source map explorer to a Create React App project, follow these steps:
1534 |
1535 | ```sh
1536 | npm install --save source-map-explorer
1537 | ```
1538 |
1539 | Alternatively you may use `yarn`:
1540 |
1541 | ```sh
1542 | yarn add source-map-explorer
1543 | ```
1544 |
1545 | Then in `package.json`, add the following line to `scripts`:
1546 |
1547 | ```diff
1548 | "scripts": {
1549 | + "analyze": "source-map-explorer build/static/js/main.*",
1550 | "start": "react-scripts start",
1551 | "build": "react-scripts build",
1552 | "test": "react-scripts test --env=jsdom",
1553 | ```
1554 |
1555 | Then to analyze the bundle run the production build then run the analyze
1556 | script.
1557 |
1558 | ```
1559 | npm run build
1560 | npm run analyze
1561 | ```
1562 |
1563 | ## Deployment
1564 |
1565 | `npm run build` creates a `build` directory with a production build of your app. Set up your favourite HTTP server so that a visitor to your site is served `index.html`, and requests to static paths like `/static/js/main..js` are served with the contents of the `/static/js/main..js` file.
1566 |
1567 | ### Static Server
1568 |
1569 | For environments using [Node](https://nodejs.org/), the easiest way to handle this would be to install [serve](https://github.com/zeit/serve) and let it handle the rest:
1570 |
1571 | ```sh
1572 | npm install -g serve
1573 | serve -s build
1574 | ```
1575 |
1576 | The last command shown above will serve your static site on the port **5000**. Like many of [serve](https://github.com/zeit/serve)’s internal settings, the port can be adjusted using the `-p` or `--port` flags.
1577 |
1578 | Run this command to get a full list of the options available:
1579 |
1580 | ```sh
1581 | serve -h
1582 | ```
1583 |
1584 | ### Other Solutions
1585 |
1586 | You don’t necessarily need a static server in order to run a Create React App project in production. It works just as fine integrated into an existing dynamic one.
1587 |
1588 | Here’s a programmatic example using [Node](https://nodejs.org/) and [Express](http://expressjs.com/):
1589 |
1590 | ```javascript
1591 | const express = require('express');
1592 | const path = require('path');
1593 | const app = express();
1594 |
1595 | app.use(express.static(path.join(__dirname, 'build')));
1596 |
1597 | app.get('/', function (req, res) {
1598 | res.sendFile(path.join(__dirname, 'build', 'index.html'));
1599 | });
1600 |
1601 | app.listen(9000);
1602 | ```
1603 |
1604 | The choice of your server software isn’t important either. Since Create React App is completely platform-agnostic, there’s no need to explicitly use Node.
1605 |
1606 | The `build` folder with static assets is the only output produced by Create React App.
1607 |
1608 | However this is not quite enough if you use client-side routing. Read the next section if you want to support URLs like `/todos/42` in your single-page app.
1609 |
1610 | ### Serving Apps with Client-Side Routing
1611 |
1612 | If you use routers that use the HTML5 [`pushState` history API](https://developer.mozilla.org/en-US/docs/Web/API/History_API#Adding_and_modifying_history_entries) under the hood (for example, [React Router](https://github.com/ReactTraining/react-router) with `browserHistory`), many static file servers will fail. For example, if you used React Router with a route for `/todos/42`, the development server will respond to `localhost:3000/todos/42` properly, but an Express serving a production build as above will not.
1613 |
1614 | This is because when there is a fresh page load for a `/todos/42`, the server looks for the file `build/todos/42` and does not find it. The server needs to be configured to respond to a request to `/todos/42` by serving `index.html`. For example, we can amend our Express example above to serve `index.html` for any unknown paths:
1615 |
1616 | ```diff
1617 | app.use(express.static(path.join(__dirname, 'build')));
1618 |
1619 | -app.get('/', function (req, res) {
1620 | +app.get('/*', function (req, res) {
1621 | res.sendFile(path.join(__dirname, 'build', 'index.html'));
1622 | });
1623 | ```
1624 |
1625 | If you’re using [Apache HTTP Server](https://httpd.apache.org/), you need to create a `.htaccess` file in the `public` folder that looks like this:
1626 |
1627 | ```
1628 | Options -MultiViews
1629 | RewriteEngine On
1630 | RewriteCond %{REQUEST_FILENAME} !-f
1631 | RewriteRule ^ index.html [QSA,L]
1632 | ```
1633 |
1634 | It will get copied to the `build` folder when you run `npm run build`.
1635 |
1636 | If you’re using [Apache Tomcat](http://tomcat.apache.org/), you need to follow [this Stack Overflow answer](https://stackoverflow.com/a/41249464/4878474).
1637 |
1638 | Now requests to `/todos/42` will be handled correctly both in development and in production.
1639 |
1640 | On a production build, and in a browser that supports [service workers](https://developers.google.com/web/fundamentals/getting-started/primers/service-workers),
1641 | the service worker will automatically handle all navigation requests, like for
1642 | `/todos/42`, by serving the cached copy of your `index.html`. This
1643 | service worker navigation routing can be configured or disabled by
1644 | [`eject`ing](#npm-run-eject) and then modifying the
1645 | [`navigateFallback`](https://github.com/GoogleChrome/sw-precache#navigatefallback-string)
1646 | and [`navigateFallbackWhitelist`](https://github.com/GoogleChrome/sw-precache#navigatefallbackwhitelist-arrayregexp)
1647 | options of the `SWPreachePlugin` [configuration](../config/webpack.config.prod.js).
1648 |
1649 | ### Building for Relative Paths
1650 |
1651 | By default, Create React App produces a build assuming your app is hosted at the server root.
1652 | To override this, specify the `homepage` in your `package.json`, for example:
1653 |
1654 | ```js
1655 | "homepage": "http://mywebsite.com/relativepath",
1656 | ```
1657 |
1658 | This will let Create React App correctly infer the root path to use in the generated HTML file.
1659 |
1660 | **Note**: If you are using `react-router@^4`, you can root ` `s using the `basename` prop on any ``.
1661 | More information [here](https://reacttraining.com/react-router/web/api/BrowserRouter/basename-string).
1662 |
1663 | For example:
1664 | ```js
1665 |
1666 | // renders
1667 | ```
1668 |
1669 | #### Serving the Same Build from Different Paths
1670 |
1671 | >Note: this feature is available with `react-scripts@0.9.0` and higher.
1672 |
1673 | If you are not using the HTML5 `pushState` history API or not using client-side routing at all, it is unnecessary to specify the URL from which your app will be served. Instead, you can put this in your `package.json`:
1674 |
1675 | ```js
1676 | "homepage": ".",
1677 | ```
1678 |
1679 | This will make sure that all the asset paths are relative to `index.html`. You will then be able to move your app from `http://mywebsite.com` to `http://mywebsite.com/relativepath` or even `http://mywebsite.com/relative/path` without having to rebuild it.
1680 |
1681 | ### Azure
1682 |
1683 | See [this](https://medium.com/@to_pe/deploying-create-react-app-on-microsoft-azure-c0f6686a4321) blog post on how to deploy your React app to [Microsoft Azure](https://azure.microsoft.com/).
1684 |
1685 | ### Firebase
1686 |
1687 | Install the Firebase CLI if you haven’t already by running `npm install -g firebase-tools`. Sign up for a [Firebase account](https://console.firebase.google.com/) and create a new project. Run `firebase login` and login with your previous created Firebase account.
1688 |
1689 | Then run the `firebase init` command from your project’s root. You need to choose the **Hosting: Configure and deploy Firebase Hosting sites** and choose the Firebase project you created in the previous step. You will need to agree with `database.rules.json` being created, choose `build` as the public directory, and also agree to **Configure as a single-page app** by replying with `y`.
1690 |
1691 | ```sh
1692 | === Project Setup
1693 |
1694 | First, let's associate this project directory with a Firebase project.
1695 | You can create multiple project aliases by running firebase use --add,
1696 | but for now we'll just set up a default project.
1697 |
1698 | ? What Firebase project do you want to associate as default? Example app (example-app-fd690)
1699 |
1700 | === Database Setup
1701 |
1702 | Firebase Realtime Database Rules allow you to define how your data should be
1703 | structured and when your data can be read from and written to.
1704 |
1705 | ? What file should be used for Database Rules? database.rules.json
1706 | ✔ Database Rules for example-app-fd690 have been downloaded to database.rules.json.
1707 | Future modifications to database.rules.json will update Database Rules when you run
1708 | firebase deploy.
1709 |
1710 | === Hosting Setup
1711 |
1712 | Your public directory is the folder (relative to your project directory) that
1713 | will contain Hosting assets to uploaded with firebase deploy. If you
1714 | have a build process for your assets, use your build's output directory.
1715 |
1716 | ? What do you want to use as your public directory? build
1717 | ? Configure as a single-page app (rewrite all urls to /index.html)? Yes
1718 | ✔ Wrote build/index.html
1719 |
1720 | i Writing configuration info to firebase.json...
1721 | i Writing project information to .firebaserc...
1722 |
1723 | ✔ Firebase initialization complete!
1724 | ```
1725 |
1726 | Now, after you create a production build with `npm run build`, you can deploy it by running `firebase deploy`.
1727 |
1728 | ```sh
1729 | === Deploying to 'example-app-fd690'...
1730 |
1731 | i deploying database, hosting
1732 | ✔ database: rules ready to deploy.
1733 | i hosting: preparing build directory for upload...
1734 | Uploading: [============================== ] 75%✔ hosting: build folder uploaded successfully
1735 | ✔ hosting: 8 files uploaded successfully
1736 | i starting release process (may take several minutes)...
1737 |
1738 | ✔ Deploy complete!
1739 |
1740 | Project Console: https://console.firebase.google.com/project/example-app-fd690/overview
1741 | Hosting URL: https://example-app-fd690.firebaseapp.com
1742 | ```
1743 |
1744 | For more information see [Add Firebase to your JavaScript Project](https://firebase.google.com/docs/web/setup).
1745 |
1746 | ### GitHub Pages
1747 |
1748 | >Note: this feature is available with `react-scripts@0.2.0` and higher.
1749 |
1750 | #### Step 1: Add `homepage` to `package.json`
1751 |
1752 | **The step below is important!**
1753 | **If you skip it, your app will not deploy correctly.**
1754 |
1755 | Open your `package.json` and add a `homepage` field:
1756 |
1757 | ```js
1758 | "homepage": "https://myusername.github.io/my-app",
1759 | ```
1760 |
1761 | Create React App uses the `homepage` field to determine the root URL in the built HTML file.
1762 |
1763 | #### Step 2: Install `gh-pages` and add `deploy` to `scripts` in `package.json`
1764 |
1765 | Now, whenever you run `npm run build`, you will see a cheat sheet with instructions on how to deploy to GitHub Pages.
1766 |
1767 | To publish it at [https://myusername.github.io/my-app](https://myusername.github.io/my-app), run:
1768 |
1769 | ```sh
1770 | npm install --save gh-pages
1771 | ```
1772 |
1773 | Alternatively you may use `yarn`:
1774 |
1775 | ```sh
1776 | yarn add gh-pages
1777 | ```
1778 |
1779 | Add the following scripts in your `package.json`:
1780 |
1781 | ```diff
1782 | "scripts": {
1783 | + "predeploy": "npm run build",
1784 | + "deploy": "gh-pages -d build",
1785 | "start": "react-scripts start",
1786 | "build": "react-scripts build",
1787 | ```
1788 |
1789 | The `predeploy` script will run automatically before `deploy` is run.
1790 |
1791 | #### Step 3: Deploy the site by running `npm run deploy`
1792 |
1793 | Then run:
1794 |
1795 | ```sh
1796 | npm run deploy
1797 | ```
1798 |
1799 | #### Step 4: Ensure your project’s settings use `gh-pages`
1800 |
1801 | Finally, make sure **GitHub Pages** option in your GitHub project settings is set to use the `gh-pages` branch:
1802 |
1803 |
1804 |
1805 | #### Step 5: Optionally, configure the domain
1806 |
1807 | You can configure a custom domain with GitHub Pages by adding a `CNAME` file to the `public/` folder.
1808 |
1809 | #### Notes on client-side routing
1810 |
1811 | GitHub Pages doesn’t support routers that use the HTML5 `pushState` history API under the hood (for example, React Router using `browserHistory`). This is because when there is a fresh page load for a url like `http://user.github.io/todomvc/todos/42`, where `/todos/42` is a frontend route, the GitHub Pages server returns 404 because it knows nothing of `/todos/42`. If you want to add a router to a project hosted on GitHub Pages, here are a couple of solutions:
1812 |
1813 | * You could switch from using HTML5 history API to routing with hashes. If you use React Router, you can switch to `hashHistory` for this effect, but the URL will be longer and more verbose (for example, `http://user.github.io/todomvc/#/todos/42?_k=yknaj`). [Read more](https://reacttraining.com/react-router/web/api/Router) about different history implementations in React Router.
1814 | * Alternatively, you can use a trick to teach GitHub Pages to handle 404 by redirecting to your `index.html` page with a special redirect parameter. You would need to add a `404.html` file with the redirection code to the `build` folder before deploying your project, and you’ll need to add code handling the redirect parameter to `index.html`. You can find a detailed explanation of this technique [in this guide](https://github.com/rafrex/spa-github-pages).
1815 |
1816 | ### Heroku
1817 |
1818 | Use the [Heroku Buildpack for Create React App](https://github.com/mars/create-react-app-buildpack).
1819 | You can find instructions in [Deploying React with Zero Configuration](https://blog.heroku.com/deploying-react-with-zero-configuration).
1820 |
1821 | #### Resolving Heroku Deployment Errors
1822 |
1823 | Sometimes `npm run build` works locally but fails during deploy via Heroku. Following are the most common cases.
1824 |
1825 | ##### "Module not found: Error: Cannot resolve 'file' or 'directory'"
1826 |
1827 | If you get something like this:
1828 |
1829 | ```
1830 | remote: Failed to create a production build. Reason:
1831 | remote: Module not found: Error: Cannot resolve 'file' or 'directory'
1832 | MyDirectory in /tmp/build_1234/src
1833 | ```
1834 |
1835 | It means you need to ensure that the lettercase of the file or directory you `import` matches the one you see on your filesystem or on GitHub.
1836 |
1837 | This is important because Linux (the operating system used by Heroku) is case sensitive. So `MyDirectory` and `mydirectory` are two distinct directories and thus, even though the project builds locally, the difference in case breaks the `import` statements on Heroku remotes.
1838 |
1839 | ##### "Could not find a required file."
1840 |
1841 | If you exclude or ignore necessary files from the package you will see a error similar this one:
1842 |
1843 | ```
1844 | remote: Could not find a required file.
1845 | remote: Name: `index.html`
1846 | remote: Searched in: /tmp/build_a2875fc163b209225122d68916f1d4df/public
1847 | remote:
1848 | remote: npm ERR! Linux 3.13.0-105-generic
1849 | remote: npm ERR! argv "/tmp/build_a2875fc163b209225122d68916f1d4df/.heroku/node/bin/node" "/tmp/build_a2875fc163b209225122d68916f1d4df/.heroku/node/bin/npm" "run" "build"
1850 | ```
1851 |
1852 | In this case, ensure that the file is there with the proper lettercase and that’s not ignored on your local `.gitignore` or `~/.gitignore_global`.
1853 |
1854 | ### Netlify
1855 |
1856 | **To do a manual deploy to Netlify’s CDN:**
1857 |
1858 | ```sh
1859 | npm install netlify-cli
1860 | netlify deploy
1861 | ```
1862 |
1863 | Choose `build` as the path to deploy.
1864 |
1865 | **To setup continuous delivery:**
1866 |
1867 | With this setup Netlify will build and deploy when you push to git or open a pull request:
1868 |
1869 | 1. [Start a new netlify project](https://app.netlify.com/signup)
1870 | 2. Pick your Git hosting service and select your repository
1871 | 3. Click `Build your site`
1872 |
1873 | **Support for client-side routing:**
1874 |
1875 | To support `pushState`, make sure to create a `public/_redirects` file with the following rewrite rules:
1876 |
1877 | ```
1878 | /* /index.html 200
1879 | ```
1880 |
1881 | When you build the project, Create React App will place the `public` folder contents into the build output.
1882 |
1883 | ### Now
1884 |
1885 | [now](https://zeit.co/now) offers a zero-configuration single-command deployment. You can use `now` to deploy your app for free.
1886 |
1887 | 1. Install the `now` command-line tool either via the recommended [desktop tool](https://zeit.co/download) or via node with `npm install -g now`.
1888 |
1889 | 2. Build your app by running `npm run build`.
1890 |
1891 | 3. Move into the build directory by running `cd build`.
1892 |
1893 | 4. Run `now --name your-project-name` from within the build directory. You will see a **now.sh** URL in your output like this:
1894 |
1895 | ```
1896 | > Ready! https://your-project-name-tpspyhtdtk.now.sh (copied to clipboard)
1897 | ```
1898 |
1899 | Paste that URL into your browser when the build is complete, and you will see your deployed app.
1900 |
1901 | Details are available in [this article.](https://zeit.co/blog/unlimited-static)
1902 |
1903 | ### S3 and CloudFront
1904 |
1905 | See this [blog post](https://medium.com/@omgwtfmarc/deploying-create-react-app-to-s3-or-cloudfront-48dae4ce0af) on how to deploy your React app to Amazon Web Services [S3](https://aws.amazon.com/s3) and [CloudFront](https://aws.amazon.com/cloudfront/).
1906 |
1907 | ### Surge
1908 |
1909 | Install the Surge CLI if you haven’t already by running `npm install -g surge`. Run the `surge` command and log in you or create a new account.
1910 |
1911 | When asked about the project path, make sure to specify the `build` folder, for example:
1912 |
1913 | ```sh
1914 | project path: /path/to/project/build
1915 | ```
1916 |
1917 | Note that in order to support routers that use HTML5 `pushState` API, you may want to rename the `index.html` in your build folder to `200.html` before deploying to Surge. This [ensures that every URL falls back to that file](https://surge.sh/help/adding-a-200-page-for-client-side-routing).
1918 |
1919 | ## Advanced Configuration
1920 |
1921 | You can adjust various development and production settings by setting environment variables in your shell or with [.env](#adding-development-environment-variables-in-env).
1922 |
1923 | | Variable | Development | Production | Usage |
1924 | | :------------------ | :--------------------: | :----------------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1925 | | BROWSER | :white_check_mark: | :x: | By default, Create React App will open the default system browser, favoring Chrome on macOS. Specify a [browser](https://github.com/sindresorhus/opn#app) to override this behavior, or set it to `none` to disable it completely. If you need to customize the way the browser is launched, you can specify a node script instead. Any arguments passed to `npm start` will also be passed to this script, and the url where your app is served will be the last argument. Your script's file name must have the `.js` extension. |
1926 | | HOST | :white_check_mark: | :x: | By default, the development web server binds to `localhost`. You may use this variable to specify a different host. |
1927 | | PORT | :white_check_mark: | :x: | By default, the development web server will attempt to listen on port 3000 or prompt you to attempt the next available port. You may use this variable to specify a different port. |
1928 | | HTTPS | :white_check_mark: | :x: | When set to `true`, Create React App will run the development server in `https` mode. |
1929 | | PUBLIC_URL | :x: | :white_check_mark: | Create React App assumes your application is hosted at the serving web server's root or a subpath as specified in [`package.json` (`homepage`)](#building-for-relative-paths). Normally, Create React App ignores the hostname. You may use this variable to force assets to be referenced verbatim to the url you provide (hostname included). This may be particularly useful when using a CDN to host your application. |
1930 | | CI | :large_orange_diamond: | :white_check_mark: | When set to `true`, Create React App treats warnings as failures in the build. It also makes the test runner non-watching. Most CIs set this flag by default. |
1931 | | REACT_EDITOR | :white_check_mark: | :x: | When an app crashes in development, you will see an error overlay with clickable stack trace. When you click on it, Create React App will try to determine the editor you are using based on currently running processes, and open the relevant source file. You can [send a pull request to detect your editor of choice](https://github.com/facebookincubator/create-react-app/issues/2636). Setting this environment variable overrides the automatic detection. If you do it, make sure your systems [PATH](https://en.wikipedia.org/wiki/PATH_(variable)) environment variable points to your editor’s bin folder. |
1932 | | CHOKIDAR_USEPOLLING | :white_check_mark: | :x: | When set to `true`, the watcher runs in polling mode, as necessary inside a VM. Use this option if `npm start` isn't detecting changes. |
1933 | | GENERATE_SOURCEMAP | :x: | :white_check_mark: | When set to `false`, source maps are not generated for a production build. This solves OOM issues on some smaller machines. |
1934 |
1935 | ## Troubleshooting
1936 |
1937 | ### `npm start` doesn’t detect changes
1938 |
1939 | When you save a file while `npm start` is running, the browser should refresh with the updated code.
1940 | If this doesn’t happen, try one of the following workarounds:
1941 |
1942 | * If your project is in a Dropbox folder, try moving it out.
1943 | * If the watcher doesn’t see a file called `index.js` and you’re referencing it by the folder name, you [need to restart the watcher](https://github.com/facebookincubator/create-react-app/issues/1164) due to a Webpack bug.
1944 | * Some editors like Vim and IntelliJ have a “safe write” feature that currently breaks the watcher. You will need to disable it. Follow the instructions in [“Adjusting Your Text Editor”](https://webpack.js.org/guides/development/#adjusting-your-text-editor).
1945 | * If your project path contains parentheses, try moving the project to a path without them. This is caused by a [Webpack watcher bug](https://github.com/webpack/watchpack/issues/42).
1946 | * On Linux and macOS, you might need to [tweak system settings](https://webpack.github.io/docs/troubleshooting.html#not-enough-watchers) to allow more watchers.
1947 | * If the project runs inside a virtual machine such as (a Vagrant provisioned) VirtualBox, create an `.env` file in your project directory if it doesn’t exist, and add `CHOKIDAR_USEPOLLING=true` to it. This ensures that the next time you run `npm start`, the watcher uses the polling mode, as necessary inside a VM.
1948 |
1949 | If none of these solutions help please leave a comment [in this thread](https://github.com/facebookincubator/create-react-app/issues/659).
1950 |
1951 | ### `npm test` hangs on macOS Sierra
1952 |
1953 | If you run `npm test` and the console gets stuck after printing `react-scripts test --env=jsdom` to the console there might be a problem with your [Watchman](https://facebook.github.io/watchman/) installation as described in [facebookincubator/create-react-app#713](https://github.com/facebookincubator/create-react-app/issues/713).
1954 |
1955 | We recommend deleting `node_modules` in your project and running `npm install` (or `yarn` if you use it) first. If it doesn't help, you can try one of the numerous workarounds mentioned in these issues:
1956 |
1957 | * [facebook/jest#1767](https://github.com/facebook/jest/issues/1767)
1958 | * [facebook/watchman#358](https://github.com/facebook/watchman/issues/358)
1959 | * [ember-cli/ember-cli#6259](https://github.com/ember-cli/ember-cli/issues/6259)
1960 |
1961 | It is reported that installing Watchman 4.7.0 or newer fixes the issue. If you use [Homebrew](http://brew.sh/), you can run these commands to update it:
1962 |
1963 | ```
1964 | watchman shutdown-server
1965 | brew update
1966 | brew reinstall watchman
1967 | ```
1968 |
1969 | You can find [other installation methods](https://facebook.github.io/watchman/docs/install.html#build-install) on the Watchman documentation page.
1970 |
1971 | If this still doesn’t help, try running `launchctl unload -F ~/Library/LaunchAgents/com.github.facebook.watchman.plist`.
1972 |
1973 | There are also reports that *uninstalling* Watchman fixes the issue. So if nothing else helps, remove it from your system and try again.
1974 |
1975 | ### `npm run build` exits too early
1976 |
1977 | It is reported that `npm run build` can fail on machines with limited memory and no swap space, which is common in cloud environments. Even with small projects this command can increase RAM usage in your system by hundreds of megabytes, so if you have less than 1 GB of available memory your build is likely to fail with the following message:
1978 |
1979 | > 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.
1980 |
1981 | If you are completely sure that you didn't terminate the process, consider [adding some swap space](https://www.digitalocean.com/community/tutorials/how-to-add-swap-on-ubuntu-14-04) to the machine you’re building on, or build the project locally.
1982 |
1983 | ### `npm run build` fails on Heroku
1984 |
1985 | This may be a problem with case sensitive filenames.
1986 | Please refer to [this section](#resolving-heroku-deployment-errors).
1987 |
1988 | ### Moment.js locales are missing
1989 |
1990 | If you use a [Moment.js](https://momentjs.com/), you might notice that only the English locale is available by default. This is because the locale files are large, and you probably only need a subset of [all the locales provided by Moment.js](https://momentjs.com/#multiple-locale-support).
1991 |
1992 | To add a specific Moment.js locale to your bundle, you need to import it explicitly.
1993 | For example:
1994 |
1995 | ```js
1996 | import moment from 'moment';
1997 | import 'moment/locale/fr';
1998 | ```
1999 |
2000 | If import multiple locales this way, you can later switch between them by calling `moment.locale()` with the locale name:
2001 |
2002 | ```js
2003 | import moment from 'moment';
2004 | import 'moment/locale/fr';
2005 | import 'moment/locale/es';
2006 |
2007 | // ...
2008 |
2009 | moment.locale('fr');
2010 | ```
2011 |
2012 | This will only work for locales that have been explicitly imported before.
2013 |
2014 | ### `npm run build` fails to minify
2015 |
2016 | You may occasionally find a package you depend on needs compiled or ships code for a non-browser environment.
2017 | This is considered poor practice in the ecosystem and does not have an escape hatch in Create React App.
2018 |
2019 | To resolve this:
2020 | 1. Open an issue on the dependency's issue tracker and ask that the package be published pre-compiled (retaining ES6 Modules).
2021 | 2. Fork the package and publish a corrected version yourself.
2022 | 3. If the dependency is small enough, copy it to your `src/` folder and treat it as application code.
2023 |
2024 | ## Something Missing?
2025 |
2026 | If you have ideas for more “How To” recipes that should be on this page, [let us know](https://github.com/facebookincubator/create-react-app/issues) or [contribute some!](https://github.com/facebookincubator/create-react-app/edit/master/packages/react-scripts/template/README.md)
2027 |
--------------------------------------------------------------------------------
/example/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "react-use-downloader-example",
3 | "homepage": "https://the-bugging.github.io/react-use-downloader",
4 | "version": "0.0.0",
5 | "license": "MIT",
6 | "private": true,
7 | "dependencies": {
8 | "@material-ui/core": "^4.12.4",
9 | "react": "file:../node_modules/react",
10 | "react-dom": "^17.0.2",
11 | "react-scripts": "file:../node_modules/react-scripts",
12 | "react-use-downloader": "file:.."
13 | },
14 | "scripts": {
15 | "start": "react-scripts start",
16 | "build": "react-scripts build",
17 | "test": "react-scripts test --env=jsdom",
18 | "eject": "react-scripts eject"
19 | },
20 | "browserslist": [
21 | ">0.2%",
22 | "not dead",
23 | "not ie <= 11",
24 | "not op_mini all"
25 | ]
26 | }
27 |
--------------------------------------------------------------------------------
/example/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 | react-use-downloader
11 |
12 |
13 |
14 |
15 | You need to enable JavaScript to run this app.
16 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/example/public/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "short_name": "react-use-downloader",
3 | "name": "react-use-downloader",
4 | "start_url": "./index.html",
5 | "display": "standalone",
6 | "theme_color": "#000000",
7 | "background_color": "#ffffff"
8 | }
9 |
--------------------------------------------------------------------------------
/example/src/App.jsx:
--------------------------------------------------------------------------------
1 | import {
2 | Button,
3 | Card,
4 | CardActions,
5 | CardContent,
6 | LinearProgress,
7 | Typography,
8 | makeStyles,
9 | } from '@material-ui/core';
10 | import useDownloader from 'react-use-downloader';
11 |
12 | const useStyles = makeStyles({
13 | root: {
14 | maxWidth: 390,
15 | margin: '4rem auto',
16 | },
17 | list: {
18 | padding: '0 1.5rem',
19 | },
20 | });
21 |
22 | export default function App() {
23 | const classes = useStyles();
24 | const { size, elapsed, percentage, download, cancel, error, isInProgress } =
25 | useDownloader();
26 |
27 | const fileUrl =
28 | 'https://upload.wikimedia.org/wikipedia/commons/4/4d/%D0%93%D0%BE%D0%B2%D0%B5%D1%80%D0%BB%D0%B0_%D1%96_%D0%9F%D0%B5%D1%82%D1%80%D0%BE%D1%81_%D0%B2_%D0%BF%D1%80%D0%BE%D0%BC%D1%96%D0%BD%D1%8F%D1%85_%D0%B2%D1%80%D0%B0%D0%BD%D1%96%D1%88%D0%BD%D1%8C%D0%BE%D0%B3%D0%BE_%D1%81%D0%BE%D0%BD%D1%86%D1%8F.jpg';
29 | const filename = 'beautiful-carpathia.jpg';
30 |
31 | return (
32 |
33 |
34 |
35 | react-use-downloader
36 |
37 |
43 | Creates a download handler function and gives progress information
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 | size: {size} bytes
52 |
53 |
54 |
55 |
56 | elapsed: {elapsed}s
57 |
58 |
59 |
60 |
61 | percentage: {percentage}%
62 |
63 |
64 |
65 |
66 | error: {JSON.stringify(error)}
67 |
68 |
69 |
70 |
71 | isInProgress: {isInProgress.toString()}
72 |
73 |
74 |
75 |
76 |
77 | download(fileUrl, filename)}
82 | >
83 | Download file
84 |
85 | cancel()}
90 | >
91 | Cancel the download
92 |
93 |
94 |
95 | );
96 | }
97 |
--------------------------------------------------------------------------------
/example/src/index.jsx:
--------------------------------------------------------------------------------
1 | import ReactDOM from 'react-dom';
2 |
3 | import App from './App';
4 |
5 | ReactDOM.render( , document.getElementById('root'));
6 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "react-use-downloader",
3 | "version": "1.2.10",
4 | "description": "Creates a download handler function and gives progress information",
5 | "author": "Olavo Parno",
6 | "license": "MIT",
7 | "repository": {
8 | "type": "git",
9 | "url": "git://github.com/the-bugging/react-use-downloader.git"
10 | },
11 | "main": "dist/index.js",
12 | "module": "dist/index.es.js",
13 | "types": "dist/index.d.ts",
14 | "jsnext:main": "dist/index.es.js",
15 | "engines": {
16 | "node": ">=8",
17 | "npm": ">=5"
18 | },
19 | "files": [
20 | "LICENSE",
21 | "README.md",
22 | "dist/"
23 | ],
24 | "lint-staged": {
25 | "*.ts": [
26 | "eslint --fix src/**/*.ts"
27 | ]
28 | },
29 | "scripts": {
30 | "test": "react-scripts test",
31 | "test:coverage": "npm run test -- --coverage --watchAll=false",
32 | "prebuild": "node clean.js dist",
33 | "build": "rollup -c && tsc -d --emitDeclarationOnly --noEmit false --declarationDir dist",
34 | "start": "rollup -c -w",
35 | "prepare": "husky install",
36 | "predeploy": "cd example && npm install && npm run build",
37 | "deploy": "gh-pages -d example/build",
38 | "format": "prettier --write src/**/*.ts",
39 | "lint": "eslint --fix src/**/*.ts",
40 | "release": "standard-version",
41 | "make-badges": "istanbul-badges-readme --logo=jest",
42 | "prepublishOnly": "npm run build"
43 | },
44 | "jest": {
45 | "coverageReporters": [
46 | "lcov",
47 | "json-summary"
48 | ]
49 | },
50 | "peerDependencies": {
51 | "react": "^17.0.2 || ^18.0.0 || ^19.0.0"
52 | },
53 | "devDependencies": {
54 | "@babel/core": "^7.16.12",
55 | "@babel/runtime": "^7.16.7",
56 | "@rollup/plugin-babel": "^5.3.0",
57 | "@rollup/plugin-commonjs": "^21.0.1",
58 | "@rollup/plugin-node-resolve": "^13.1.3",
59 | "@rollup/plugin-typescript": "^8.3.0",
60 | "@rollup/plugin-url": "^6.1.0",
61 | "@testing-library/react-hooks": "^7.0.2",
62 | "@types/jest": "^27.4.0",
63 | "@types/node-fetch": "^3.0.3",
64 | "@types/react": "^17.0.38",
65 | "@typescript-eslint/eslint-plugin": "^5.10.1",
66 | "@typescript-eslint/parser": "^5.10.1",
67 | "all-contributors-cli": "^6.26.1",
68 | "cross-env": "^7.0.3",
69 | "eslint": "^8.7.0",
70 | "eslint-config-airbnb": "^19.0.4",
71 | "eslint-config-airbnb-typescript-prettier": "^5.0.0",
72 | "eslint-config-prettier": "^8.3.0",
73 | "eslint-plugin-import": "^2.25.4",
74 | "eslint-plugin-jsx-a11y": "^6.5.1",
75 | "eslint-plugin-prettier": "^4.0.0",
76 | "eslint-plugin-react": "^7.28.0",
77 | "eslint-plugin-react-hooks": "^4.3.0",
78 | "gh-pages": "^3.2.3",
79 | "husky": "^7.0.4",
80 | "istanbul-badges-readme": "^1.8.1",
81 | "node-fetch": "^3.2.0",
82 | "prettier": "^2.5.1",
83 | "react": "^17.0.2",
84 | "react-scripts": "^5.0.1",
85 | "react-test-renderer": "^17.0.2",
86 | "rollup": "^2.66.1",
87 | "rollup-plugin-peer-deps-external": "^2.2.4",
88 | "rollup-plugin-terser": "^7.0.2",
89 | "standard-version": "^9.3.2",
90 | "tslib": "^2.3.1",
91 | "typescript": "^4.5.5",
92 | "web-streams-polyfill": "^4.1.0"
93 | }
94 | }
95 |
--------------------------------------------------------------------------------
/pull_request_template.md:
--------------------------------------------------------------------------------
1 | Describe what's being changed
2 |
--------------------------------------------------------------------------------
/react-use-downloader.code-workspace:
--------------------------------------------------------------------------------
1 | {
2 | "folders": [
3 | {
4 | "path": "."
5 | }
6 | ],
7 | "settings": {}
8 | }
--------------------------------------------------------------------------------
/rollup.config.js:
--------------------------------------------------------------------------------
1 | import typescript from '@rollup/plugin-typescript';
2 | import commonjs from '@rollup/plugin-commonjs';
3 | import resolve from '@rollup/plugin-node-resolve';
4 | import external from 'rollup-plugin-peer-deps-external';
5 | import url from '@rollup/plugin-url';
6 | import { terser } from 'rollup-plugin-terser';
7 |
8 | import pkg from './package.json';
9 |
10 | export default {
11 | input: 'src/index.ts',
12 | output: [
13 | {
14 | file: pkg.main,
15 | format: 'cjs',
16 | exports: 'named',
17 | sourcemap: true,
18 | },
19 | {
20 | file: pkg.module,
21 | format: 'es',
22 | exports: 'named',
23 | sourcemap: true,
24 | },
25 | ],
26 | plugins: [
27 | external(),
28 | url({ exclude: ['**/*.svg'] }),
29 | resolve(),
30 | typescript(),
31 | commonjs({ extensions: ['.ts'] }),
32 | terser(),
33 | ],
34 | };
35 |
--------------------------------------------------------------------------------
/src/__tests__/index.spec.ts:
--------------------------------------------------------------------------------
1 | /* eslint-disable no-prototype-builtins */
2 | /* eslint-disable no-plusplus */
3 | import {
4 | ReadableStream,
5 | ReadableStreamDefaultReadResult,
6 | } from 'web-streams-polyfill';
7 | import { renderHook, act } from '@testing-library/react-hooks';
8 | import useDownloader, { jsDownload } from '../index';
9 | import { WindowDownloaderEmbedded } from '../types';
10 |
11 | const expectedKeys = [
12 | 'elapsed',
13 | 'percentage',
14 | 'size',
15 | 'download',
16 | 'cancel',
17 | 'error',
18 | 'isInProgress',
19 | ];
20 |
21 | beforeAll(() => {
22 | global.window.fetch = fetch as Extract;
23 | global.Response = Response;
24 | global.ReadableStream =
25 | ReadableStream as unknown as typeof global.ReadableStream;
26 | });
27 |
28 | describe('useDownloader successes', () => {
29 | beforeAll(() => {
30 | process.env.REACT_APP_DEBUG_MODE = 'true';
31 | window.URL.createObjectURL = () => 'true';
32 | window.URL.revokeObjectURL = () => 'true';
33 | window.webkitURL.createObjectURL = () => 'true';
34 |
35 | const pieces = [
36 | new Uint8Array([65, 98, 99, 32, 208]), // "Abc " and first byte of "й"
37 | new Uint8Array([185, 209, 139, 209, 141]), // Second byte of "й" and "ыэ"
38 | ];
39 |
40 | const fakeHeaders = new Headers({
41 | 'content-encoding': '',
42 | 'x-file-size': '123',
43 | 'content-length': '456',
44 | });
45 |
46 | global.window.fetch = () =>
47 | Promise.resolve({
48 | ok: true,
49 | headers: {
50 | ...fakeHeaders,
51 | get: (header) => fakeHeaders[header],
52 | },
53 | body: {
54 | getReader() {
55 | let i = 0;
56 |
57 | return {
58 | read() {
59 | return Promise.resolve<
60 | ReadableStreamDefaultReadResult
61 | >(
62 | i < pieces.length
63 | ? { value: pieces[i++], done: false }
64 | : { value: undefined, done: true }
65 | );
66 | },
67 | };
68 | },
69 | },
70 | blob: () => Promise.resolve(new Blob()),
71 | }) as Extract;
72 | });
73 |
74 | it('should run through', async () => {
75 | const { result, waitForNextUpdate } = renderHook(() => useDownloader());
76 |
77 | expect(result.current.isInProgress).toBeFalsy();
78 |
79 | act(() => {
80 | result.current.download('https://url.com', 'filename');
81 | });
82 |
83 | expect(result.current.isInProgress).toBeTruthy();
84 |
85 | await waitForNextUpdate();
86 |
87 | expect(result.current.isInProgress).toBeFalsy();
88 | });
89 | });
90 |
91 | describe('useDownloader failures', () => {
92 | beforeEach(() => {
93 | console.error = jest.fn();
94 | });
95 |
96 | it('should be defined', () => {
97 | const { result } = renderHook(() => useDownloader());
98 | expect(result).toBeDefined();
99 | });
100 |
101 | it('should return initial values', () => {
102 | const { result } = renderHook(() => useDownloader());
103 |
104 | expectedKeys.forEach((key) => {
105 | expect(result.current.hasOwnProperty(key)).toBeTruthy();
106 | });
107 | });
108 |
109 | it('should start download with no OK', async () => {
110 | const { result, waitForNextUpdate } = renderHook(() => useDownloader());
111 |
112 | global.window.fetch = () =>
113 | Promise.resolve({ ok: false }) as Extract<
114 | WindowOrWorkerGlobalScope,
115 | 'fetch'
116 | >;
117 |
118 | const downloadSpy = jest.spyOn(result.current, 'download');
119 |
120 | expect(result.current.isInProgress).toBeFalsy();
121 |
122 | act(() => {
123 | result.current.download('https://url.com', 'filename');
124 | });
125 |
126 | expect(result.current.isInProgress).toBeTruthy();
127 |
128 | await waitForNextUpdate();
129 |
130 | expect(result.current.isInProgress).toBeFalsy();
131 |
132 | expect(downloadSpy).toHaveBeenCalled();
133 | });
134 |
135 | it('should NOT start download with isInProgress', async () => {
136 | process.env.REACT_APP_DEBUG_MODE = 'true';
137 | const { result, waitForNextUpdate } = renderHook(() => useDownloader());
138 |
139 | global.window.fetch = jest.fn(() =>
140 | Promise.resolve({ ok: false })
141 | ) as Extract;
142 |
143 | const downloadSpy = jest.spyOn(result.current, 'download');
144 |
145 | expect(result.current.isInProgress).toBeFalsy();
146 |
147 | act(() => {
148 | result.current.download('https://url.com', 'filename');
149 | });
150 |
151 | const isInProgressRef = result.current.isInProgress;
152 |
153 | expect(isInProgressRef).toBeTruthy();
154 |
155 | act(() => {
156 | result.current.download('https://url2.com', 'filename 2');
157 | });
158 |
159 | expect(result.current.isInProgress).toEqual(isInProgressRef);
160 |
161 | await waitForNextUpdate();
162 |
163 | expect(result.current.isInProgress).toBeFalsy();
164 |
165 | expect(downloadSpy).toHaveBeenCalled();
166 | });
167 |
168 | it('should start download with no body', async () => {
169 | const { result, waitForNextUpdate } = renderHook(() => useDownloader());
170 |
171 | global.window.fetch = jest.fn(() =>
172 | Promise.resolve({
173 | ok: true,
174 | body: undefined,
175 | })
176 | ) as Extract;
177 |
178 | act(() => {
179 | result.current.download('https://url.com', 'filename');
180 | });
181 |
182 | await waitForNextUpdate();
183 |
184 | expect(result.current.error).toEqual({
185 | errorMessage: 'ReadableStream not yet supported in this browser.',
186 | });
187 | });
188 |
189 | it('should start download with error', async () => {
190 | const { result, waitForNextUpdate } = renderHook(() => useDownloader());
191 |
192 | global.window.fetch = jest.fn(() =>
193 | Promise.reject(new Error('Custom error!'))
194 | );
195 |
196 | expect(result.current.error).toBeNull();
197 |
198 | act(() => {
199 | result.current.download('https://url.com', 'filename');
200 | });
201 |
202 | await waitForNextUpdate();
203 |
204 | expect(result.current.error).toEqual({ errorMessage: 'Custom error!' });
205 | });
206 |
207 | it('should start download with response.ok false and an error from the response', async () => {
208 | const { result, waitForNextUpdate } = renderHook(() => useDownloader());
209 |
210 | global.window.fetch = jest.fn(() =>
211 | Promise.resolve(
212 | new Response(
213 | JSON.stringify({
214 | error: 'File download not allowed',
215 | reason:
216 | 'User must complete verification before accessing this file.',
217 | }),
218 | {
219 | status: 403,
220 | statusText: 'Forbidden',
221 | headers: { 'Content-Type': 'application/json' },
222 | }
223 | )
224 | )
225 | );
226 |
227 | expect(result.current.error).toBeNull();
228 |
229 | act(() => {
230 | result.current.download('https://url.com', 'filename');
231 | });
232 |
233 | await waitForNextUpdate();
234 |
235 | expect(console.error).toHaveBeenCalledWith('403 default Forbidden');
236 |
237 | expect(result.current.error).toEqual({
238 | errorMessage:
239 | '403 - Forbidden: File download not allowed: User must complete verification before accessing this file.',
240 | });
241 | });
242 |
243 | describe('Tests with msSaveBlob', () => {
244 | beforeAll(() => {
245 | (window as unknown as WindowDownloaderEmbedded).navigator.msSaveBlob =
246 | () => {
247 | return true;
248 | };
249 | });
250 |
251 | it('should test with msSaveBlob', () => {
252 | console.error = jest.fn();
253 | const msSaveBlobSpy = jest.spyOn(
254 | (window as unknown as WindowDownloaderEmbedded).navigator,
255 | 'msSaveBlob'
256 | );
257 |
258 | jsDownload(new Blob(['abcde']), 'test');
259 |
260 | expect(msSaveBlobSpy).toHaveBeenCalled();
261 | });
262 | });
263 |
264 | describe('Tests without msSaveBlob', () => {
265 | beforeAll(() => {
266 | const currentWindow = window as unknown as WindowDownloaderEmbedded;
267 |
268 | currentWindow.navigator.msSaveBlob = undefined;
269 |
270 | if (currentWindow.URL) {
271 | currentWindow.URL.createObjectURL = () => null;
272 | currentWindow.URL.revokeObjectURL = () => null;
273 | }
274 | });
275 |
276 | it('should test with URL and being revoked', async () => {
277 | jest.useFakeTimers('modern');
278 |
279 | const createObjectURLSpy = jest.spyOn(window.URL, 'createObjectURL');
280 | const revokeObjectURLSpy = jest.spyOn(window.URL, 'revokeObjectURL');
281 |
282 | jsDownload(new Blob(['abcde']), 'test');
283 |
284 | expect(createObjectURLSpy).toHaveBeenCalled();
285 |
286 | jest.runAllTimers();
287 |
288 | expect(revokeObjectURLSpy).toHaveBeenCalled();
289 | });
290 |
291 | it('should test with URL via webkitURL', () => {
292 | const currentWindow = window as unknown as WindowDownloaderEmbedded;
293 |
294 | currentWindow.URL = undefined;
295 |
296 | if (currentWindow.webkitURL) {
297 | currentWindow.webkitURL.createObjectURL = () => null;
298 |
299 | const createObjectWebkitURLSpy = jest.spyOn(
300 | window.webkitURL,
301 | 'createObjectURL'
302 | );
303 |
304 | jsDownload(new Blob(['abcde']), 'test');
305 |
306 | expect(createObjectWebkitURLSpy).toHaveBeenCalled();
307 | }
308 | });
309 | });
310 | });
311 |
--------------------------------------------------------------------------------
/src/index.ts:
--------------------------------------------------------------------------------
1 | import { useCallback, useMemo, useRef, useState } from 'react';
2 | import {
3 | DownloadFunction,
4 | ResolverProps,
5 | UseDownloader,
6 | WindowDownloaderEmbedded,
7 | ErrorMessage,
8 | UseDownloaderOptions,
9 | } from './types';
10 |
11 | /**
12 | * Resolver function to handle the download progress.
13 | * @param {ResolverProps} props
14 | * @returns {Response}
15 | */
16 | export const resolver =
17 | ({
18 | setSize,
19 | setControllerCallback,
20 | setPercentageCallback,
21 | setErrorCallback,
22 | }: ResolverProps) =>
23 | (response: Response): Response => {
24 | if (!response.ok) {
25 | console.error(`${response.status} ${response.type} ${response.statusText}`);
26 |
27 | throw response;
28 | }
29 |
30 | if (!response.body) {
31 | throw Error('ReadableStream not yet supported in this browser.');
32 | }
33 |
34 | const responseBody = response.body;
35 |
36 | const contentEncoding = response.headers.get('content-encoding');
37 | const contentLength = response.headers.get(
38 | contentEncoding ? 'x-file-size' : 'content-length'
39 | );
40 |
41 | const total = parseInt(contentLength || '0', 10);
42 |
43 | setSize(() => total);
44 |
45 | let loaded = 0;
46 |
47 | const stream = new ReadableStream({
48 | start(controller) {
49 | setControllerCallback(controller);
50 |
51 | const reader = responseBody.getReader();
52 |
53 | async function read(): Promise {
54 | return reader
55 | .read()
56 | .then(({ done, value }) => {
57 | if (done) {
58 | return controller.close();
59 | }
60 |
61 | loaded += value?.byteLength || 0;
62 |
63 | if (value) {
64 | controller.enqueue(value);
65 | }
66 |
67 | setPercentageCallback({ loaded, total });
68 |
69 | return read();
70 | })
71 | .catch((error: Error) => {
72 | setErrorCallback(error);
73 | reader.cancel('Cancelled');
74 |
75 | return controller.error(error);
76 | });
77 | }
78 |
79 | return read();
80 | },
81 | });
82 |
83 | return new Response(stream);
84 | };
85 |
86 | /**
87 | * jsDownload function to handle the download process.
88 | * @param {Blob} data
89 | * @param {string} filename
90 | * @param {string} mime
91 | * @returns {boolean | NodeJS.Timeout}
92 | */
93 | export const jsDownload = (
94 | data: Blob,
95 | filename: string,
96 | mime?: string
97 | ): boolean | NodeJS.Timeout => {
98 | const blobData = [data];
99 | const blob = new Blob(blobData, {
100 | type: mime || 'application/octet-stream',
101 | });
102 |
103 | const currentWindow = window as unknown as WindowDownloaderEmbedded;
104 |
105 | if (
106 | typeof currentWindow.navigator
107 | .msSaveBlob !== 'undefined'
108 | ) {
109 | return currentWindow.navigator.msSaveBlob(
110 | blob,
111 | filename
112 | );
113 | }
114 |
115 | const blobURL =
116 | window.URL && window.URL.createObjectURL
117 | ? window.URL.createObjectURL(blob)
118 | : window.webkitURL.createObjectURL(blob);
119 | const tempLink = document.createElement('a');
120 | tempLink.style.display = 'none';
121 | tempLink.href = blobURL;
122 | tempLink.setAttribute('download', filename);
123 |
124 | if (typeof tempLink.download === 'undefined') {
125 | tempLink.setAttribute('target', '_blank');
126 | }
127 |
128 | document.body.appendChild(tempLink);
129 | tempLink.click();
130 |
131 | return setTimeout(() => {
132 | document.body.removeChild(tempLink);
133 | window.URL.revokeObjectURL(blobURL);
134 | }, 200);
135 | };
136 |
137 | /**
138 | * useDownloader hook to handle the download process.
139 | * @param {UseDownloaderOptions} options
140 | * @returns {UseDownloader}
141 | */
142 | export default function useDownloader(
143 | options: UseDownloaderOptions = {}
144 | ): UseDownloader {
145 | let debugMode = false;
146 | try {
147 | debugMode = process ? !!process?.env?.REACT_APP_DEBUG_MODE : false;
148 | } catch {
149 | debugMode = false;
150 | }
151 |
152 | const [elapsed, setElapsed] = useState(0);
153 | const [percentage, setPercentage] = useState(0);
154 | const [size, setSize] = useState(0);
155 | const [error, setError] = useState(null);
156 | const [isInProgress, setIsInProgress] = useState(false);
157 |
158 | const controllerRef = useRef>(
159 | null
160 | );
161 |
162 | const setPercentageCallback = useCallback(({ loaded, total }) => {
163 | const pct = Math.round((loaded / total) * 100);
164 |
165 | setPercentage(() => pct);
166 | }, []);
167 |
168 | const setErrorCallback = useCallback((err: Error) => {
169 | const errorMap = {
170 | "Failed to execute 'enqueue' on 'ReadableStreamDefaultController': Cannot enqueue a chunk into an errored readable stream":
171 | 'Download canceled',
172 | 'The user aborted a request.': 'Download timed out',
173 | };
174 | setError(() => {
175 | const resolvedError = errorMap[err.message as keyof typeof errorMap]
176 | ? errorMap[err.message as keyof typeof errorMap]
177 | : err.message;
178 |
179 | return { errorMessage: resolvedError };
180 | });
181 | }, []);
182 |
183 | const setControllerCallback = useCallback(
184 | (controller: ReadableStreamController | null) => {
185 | controllerRef.current = controller;
186 | },
187 | []
188 | );
189 |
190 | const closeControllerCallback = useCallback(() => {
191 | if (controllerRef.current) {
192 | controllerRef.current.error();
193 | }
194 | }, []);
195 |
196 | const clearAllStateCallback = useCallback(() => {
197 | setControllerCallback(null);
198 |
199 | setElapsed(() => 0);
200 | setPercentage(() => 0);
201 | setSize(() => 0);
202 | setIsInProgress(() => false);
203 | }, [setControllerCallback]);
204 |
205 | const handleDownload: DownloadFunction = useCallback(
206 | async (downloadUrl, filename, timeout = 0, overrideOptions = {}) => {
207 | if (isInProgress) return null;
208 |
209 | clearAllStateCallback();
210 | setError(() => null);
211 | setIsInProgress(() => true);
212 |
213 | const intervalId = setInterval(
214 | () => setElapsed((prevValue) => prevValue + 1),
215 | debugMode ? 1 : 1000
216 | );
217 | const resolverWithProgress = resolver({
218 | setSize,
219 | setControllerCallback,
220 | setPercentageCallback,
221 | setErrorCallback,
222 | });
223 |
224 | const fetchController = new AbortController();
225 | const timeoutId = setTimeout(() => {
226 | if (timeout > 0) fetchController.abort();
227 | }, timeout);
228 |
229 | return fetch(downloadUrl, {
230 | method: 'GET',
231 | ...options,
232 | ...overrideOptions,
233 | signal: fetchController.signal,
234 | })
235 | .then(resolverWithProgress)
236 | .then((data) => {
237 | return data.blob();
238 | })
239 | .then((response) => jsDownload(response, filename))
240 | .then(() => {
241 | clearAllStateCallback();
242 |
243 | return clearInterval(intervalId);
244 | })
245 | .catch(async (error) => {
246 | clearAllStateCallback();
247 |
248 |
249 | const errorMessage = await (async () => {
250 | if (error instanceof Response) {
251 | const contentType = error.headers.get("Content-Type") || "";
252 | const isJson = contentType.includes("application/json");
253 |
254 | const errorBody = isJson
255 | ? await error.json().catch(() => null)
256 | : await error.text().catch(() => null);
257 |
258 | return [
259 | `${error.status} - ${error.statusText}`,
260 | errorBody?.error,
261 | errorBody?.reason || (typeof errorBody === "string" ? errorBody : null),
262 | ]
263 | .filter(Boolean)
264 | .join(": ");
265 | }
266 |
267 | return error?.message || "An unknown error occurred.";
268 | })();
269 |
270 | setError({ errorMessage });
271 |
272 | clearTimeout(timeoutId);
273 | clearInterval(intervalId);
274 | });
275 |
276 | },
277 | [
278 | isInProgress,
279 | clearAllStateCallback,
280 | debugMode,
281 | setControllerCallback,
282 | setPercentageCallback,
283 | setErrorCallback,
284 | options,
285 | ]
286 | );
287 |
288 | return useMemo(
289 | () => ({
290 | elapsed,
291 | percentage,
292 | size,
293 | download: handleDownload,
294 | cancel: closeControllerCallback,
295 | error,
296 | isInProgress,
297 | }),
298 | [
299 | elapsed,
300 | percentage,
301 | size,
302 | handleDownload,
303 | closeControllerCallback,
304 | error,
305 | isInProgress,
306 | ]
307 | );
308 | }
309 |
--------------------------------------------------------------------------------
/src/react-app-env.d.ts:
--------------------------------------------------------------------------------
1 | ///
2 |
--------------------------------------------------------------------------------
/src/types.ts:
--------------------------------------------------------------------------------
1 | import { SetStateAction } from 'react';
2 |
3 | export type ErrorMessage = {
4 | errorMessage: string;
5 | } | null;
6 |
7 | /** useDownloader options for fetch call
8 | * See fetch RequestInit for more details
9 | */
10 | export type UseDownloaderOptions = RequestInit;
11 |
12 | /**
13 | * Initiate the download of the specified asset from the specified url. Optionally supply timeout and overrideOptions.
14 | * @example await download('https://example.com/file.zip', 'file.zip')
15 | * @example await download('https://example.com/file.zip', 'file.zip', 500) timeouts after 500ms
16 | * @example await download('https://example.com/file.zip', 'file.zip', undefined, { method: 'GET' }) skips optional timeout but supplies overrideOptions
17 | */
18 | export type DownloadFunction = (
19 | /** Download url
20 | * @example https://upload.wikimedia.org/wikipedia/commons/4/4d/%D0%93%D0%BE%D0%B2%D0%B5%D1%80%D0%BB%D0%B0_%D1%96_%D0%9F%D0%B5%D1%82%D1%80%D0%BE%D1%81_%D0%B2_%D0%BF%D1%80%D0%BE%D0%BC%D1%96%D0%BD%D1%8F%D1%85_%D0%B2%D1%80%D0%B0%D0%BD%D1%96%D1%88%D0%BD%D1%8C%D0%BE%D0%B3%D0%BE_%D1%81%D0%BE%D0%BD%D1%86%D1%8F.jpg
21 | */
22 | downloadUrl: string,
23 | /** File name
24 | * @example carpathia.jpeg
25 | */
26 | filename: string,
27 | /** Optional timeout to download items */
28 | timeout?: number,
29 | /** Optional options to supplement and/or override UseDownloader options */
30 | overrideOptions?: UseDownloaderOptions
31 | ) => Promise;
32 |
33 | /**
34 | * Provides access to Downloader functionality and settings.
35 | *
36 | * @interface EditDialogField
37 | * @field {number} size in bytes.
38 | * @field {number} elapsed time in seconds.
39 | * @field {number} percentage in string
40 | * @field {DownloadFunction} download function handler
41 | * @field {void} cancel function handler
42 | * @field {ErrorMessage} error object from the request
43 | * @field {boolean} isInProgress boolean flag denoting download status
44 | */
45 | export interface UseDownloader {
46 | /** Size in bytes */
47 | size: number;
48 | /** Elapsed time in seconds */
49 | elapsed: number;
50 | /** Percentage in string */
51 | percentage: number;
52 | /**
53 | * Download function handler
54 | * @example await download('https://example.com/file.zip', 'file.zip')
55 | * @example await download('https://example.com/file.zip', 'file.zip', 500) timeouts after 500ms
56 | * */
57 | download: DownloadFunction;
58 | /** Cancel function handler */
59 | cancel: () => void;
60 | /** Error object from the request */
61 | error: ErrorMessage;
62 | /** Boolean denoting download status */
63 | isInProgress: boolean;
64 | }
65 |
66 | export interface ResolverProps {
67 | setSize: (value: SetStateAction) => void;
68 | setControllerCallback: (
69 | controller: ReadableStreamController
70 | ) => void;
71 | setPercentageCallback: ({
72 | loaded,
73 | total,
74 | }: {
75 | loaded: number;
76 | total: number;
77 | }) => void;
78 | setErrorCallback: (err: Error) => void;
79 | }
80 |
81 | interface CustomNavigator extends Navigator {
82 | msSaveBlob?: (blob?: Blob, filename?: string) => boolean | NodeJS.Timeout;
83 | }
84 |
85 | interface CustomURL extends URL {
86 | createObjectURL: (blob: Blob) => string | null;
87 | revokeObjectURL: (url: string) => void | null;
88 | }
89 |
90 | export interface WindowDownloaderEmbedded extends Window {
91 | navigator: CustomNavigator;
92 | URL?: CustomURL
93 | webkitURL?: CustomURL
94 | }
95 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "module": "esnext",
4 | "target": "es5",
5 | "lib": [
6 | "es6",
7 | "dom",
8 | "es2016",
9 | "es2017"
10 | ],
11 | "sourceMap": true,
12 | "allowJs": false,
13 | "jsx": "react-jsx",
14 | "moduleResolution": "node",
15 | "forceConsistentCasingInFileNames": true,
16 | "noImplicitReturns": true,
17 | "noImplicitThis": true,
18 | "noImplicitAny": true,
19 | "strictNullChecks": true,
20 | "noUnusedLocals": true,
21 | "noUnusedParameters": true,
22 | "skipLibCheck": true,
23 | "esModuleInterop": true,
24 | "allowSyntheticDefaultImports": true,
25 | "strict": true,
26 | "resolveJsonModule": true,
27 | "isolatedModules": true,
28 | "noEmit": true,
29 | "noFallthroughCasesInSwitch": true
30 | },
31 | "include": [
32 | "src"
33 | ],
34 | "exclude": [
35 | "node_modules",
36 | "build",
37 | "dist",
38 | "example",
39 | "rollup.config.js",
40 | "src/__tests__"
41 | ]
42 | }
43 |
--------------------------------------------------------------------------------
/tsconfig.test.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "./tsconfig.json",
3 | "compilerOptions": {
4 | "module": "commonjs"
5 | }
6 | }
--------------------------------------------------------------------------------