├── .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 | [![NPM](https://img.shields.io/npm/v/react-use-downloader.svg)](https://www.npmjs.com/package/react-use-downloader) 6 | 7 | --- 8 | 9 | | Statements | Branches | Functions | Lines | 10 | | ----------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | 11 | | ![Statements](https://img.shields.io/badge/statements-86.44%25-yellow.svg?style=flat&logo=jest) | ![Branches](https://img.shields.io/badge/branches-68.62%25-red.svg?style=flat&logo=jest) | ![Functions](https://img.shields.io/badge/functions-77.14%25-red.svg?style=flat&logo=jest) | ![Lines](https://img.shields.io/badge/lines-86.91%25-yellow.svg?style=flat&logo=jest) | 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 | | ![Example](./assets/readme.gif) | 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 | 60 | 61 |

Download size in bytes {size}

62 | 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 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 |
Eric Semeniuc
Eric Semeniuc

🤔
davdi1337
davdi1337

💻 🐛
Mauro Stepanoski
Mauro Stepanoski

🤔 💻
Sam "Betty" McKoy
Sam "Betty" McKoy

🐛
Peran Osborn
Peran Osborn

🐛 🤔
Marcos
Marcos

🐛 🤔
9swampy
9swampy

🐛 💻
Dave Carlson
Dave Carlson

🤔
Phil Taylor
Phil Taylor

🚧
Marc Römmelt
Marc Römmelt

🤔 💻
nik-webdevelop
nik-webdevelop

🤔
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 `<meta>` 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.<br> 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`.<br> 180 | Read instructions below for using assets from JavaScript and HTML. 181 | 182 | You can, however, create more top-level directories.<br> 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.<br> 192 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser. 193 | 194 | The page will reload if you make edits.<br> 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.<br> 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.<br> 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.<br> 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.<br> 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.<br> 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 `<title>` 368 | 369 | You can find the source HTML file in the `public` folder of the generated project. You may edit the `<title>` 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.<br> 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 <Button color="red" />; 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 | <div> 476 | <button onClick={this.handleClick}>Load</button> 477 | </div> 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 <div className="Button" />; 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 `<script>` tag with the compiled code will be added to it automatically during the build process. 533 | 534 | ### Adding Assets Outside of the Module System 535 | 536 | You can also add other assets to the `public` folder. 537 | 538 | Note that we normally encourage you to `import` assets in JavaScript files instead. 539 | For example, see the sections on [adding a stylesheet](#adding-a-stylesheet) and [adding images and fonts](#adding-images-fonts-and-files). 540 | This mechanism provides a number of benefits: 541 | 542 | * Scripts and stylesheets get minified and bundled together to avoid extra network requests. 543 | * Missing files cause compilation errors instead of 404 errors for your users. 544 | * Result filenames include content hashes so you don’t need to worry about browsers caching their old versions. 545 | 546 | However there is an **escape hatch** that you can use to add an asset outside of the module system. 547 | 548 | If you put a file into the `public` folder, it will **not** be processed by Webpack. Instead it will be copied into the build folder untouched. To reference assets in the `public` folder, you need to use a special variable called `PUBLIC_URL`. 549 | 550 | Inside `index.html`, you can use it like this: 551 | 552 | ```html 553 | <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico"> 554 | ``` 555 | 556 | Only files inside the `public` folder will be accessible by `%PUBLIC_URL%` prefix. If you need to use a file from `src` or `node_modules`, you’ll have to copy it there to explicitly specify your intention to make this file a part of the build. 557 | 558 | When you run `npm run build`, Create React App will substitute `%PUBLIC_URL%` with a correct absolute path so your project works even if you use client-side routing or host it at a non-root URL. 559 | 560 | In JavaScript code, you can use `process.env.PUBLIC_URL` for similar purposes: 561 | 562 | ```js 563 | render() { 564 | // Note: this is an escape hatch and should be used sparingly! 565 | // Normally we recommend using `import` for getting asset URLs 566 | // as described in “Adding Images and Fonts” above this section. 567 | return <img src={process.env.PUBLIC_URL + '/img/logo.png'} />; 568 | } 569 | ``` 570 | 571 | Keep in mind the downsides of this approach: 572 | 573 | * None of the files in `public` folder get post-processed or minified. 574 | * Missing files will not be called at compilation time, and will cause 404 errors for your users. 575 | * Result filenames won’t include content hashes so you’ll need to add query arguments or rename them every time they change. 576 | 577 | ### When to Use the `public` Folder 578 | 579 | Normally we recommend importing [stylesheets](#adding-a-stylesheet), [images, and fonts](#adding-images-fonts-and-files) from JavaScript. 580 | The `public` folder is useful as a workaround for a number of less common cases: 581 | 582 | * You need a file with a specific name in the build output, such as [`manifest.webmanifest`](https://developer.mozilla.org/en-US/docs/Web/Manifest). 583 | * You have thousands of images and need to dynamically reference their paths. 584 | * You want to include a small script like [`pace.js`](http://github.hubspot.com/pace/docs/welcome/) outside of the bundled code. 585 | * Some library may be incompatible with Webpack and you have no other option but to include it as a `<script>` tag. 586 | 587 | Note that if you add a `<script>` that declares global variables, you also need to read the next section on using them. 588 | 589 | ## Using Global Variables 590 | 591 | When you include a script in the HTML file that defines global variables and try to use one of these variables in the code, the linter will complain because it cannot see the definition of the variable. 592 | 593 | You can avoid this by reading the global variable explicitly from the `window` object, for example: 594 | 595 | ```js 596 | const $ = window.$; 597 | ``` 598 | 599 | This makes it obvious you are using a global variable intentionally rather than because of a typo. 600 | 601 | Alternatively, you can force the linter to ignore any line by adding `// eslint-disable-line` after it. 602 | 603 | ## Adding Bootstrap 604 | 605 | You don’t have to use [React Bootstrap](https://react-bootstrap.github.io) together with React but it is a popular library for integrating Bootstrap with React apps. If you need it, you can integrate it with Create React App by following these steps: 606 | 607 | Install React Bootstrap and Bootstrap from npm. React Bootstrap does not include Bootstrap CSS so this needs to be installed as well: 608 | 609 | ```sh 610 | npm install --save react-bootstrap bootstrap@3 611 | ``` 612 | 613 | Alternatively you may use `yarn`: 614 | 615 | ```sh 616 | yarn add react-bootstrap bootstrap@3 617 | ``` 618 | 619 | Import Bootstrap CSS and optionally Bootstrap theme CSS in the beginning of your ```src/index.js``` file: 620 | 621 | ```js 622 | import 'bootstrap/dist/css/bootstrap.css'; 623 | import 'bootstrap/dist/css/bootstrap-theme.css'; 624 | // Put any other imports below so that CSS from your 625 | // components takes precedence over default styles. 626 | ``` 627 | 628 | Import required React Bootstrap components within ```src/App.js``` file or your custom component files: 629 | 630 | ```js 631 | import { Navbar, Jumbotron, Button } from 'react-bootstrap'; 632 | ``` 633 | 634 | Now you are ready to use the imported React Bootstrap components within your component hierarchy defined in the render method. Here is an example [`App.js`](https://gist.githubusercontent.com/gaearon/85d8c067f6af1e56277c82d19fd4da7b/raw/6158dd991b67284e9fc8d70b9d973efe87659d72/App.js) redone using React Bootstrap. 635 | 636 | ### Using a Custom Theme 637 | 638 | Sometimes you might need to tweak the visual styles of Bootstrap (or equivalent package).<br> 639 | We suggest the following approach: 640 | 641 | * Create a new package that depends on the package you wish to customize, e.g. Bootstrap. 642 | * Add the necessary build steps to tweak the theme, and publish your package on npm. 643 | * Install your own theme npm package as a dependency of your app. 644 | 645 | Here is an example of adding a [customized Bootstrap](https://medium.com/@tacomanator/customizing-create-react-app-aa9ffb88165) that follows these steps. 646 | 647 | ## Adding Flow 648 | 649 | Flow is a static type checker that helps you write code with fewer bugs. Check out this [introduction to using static types in JavaScript](https://medium.com/@preethikasireddy/why-use-static-types-in-javascript-part-1-8382da1e0adb) if you are new to this concept. 650 | 651 | Recent versions of [Flow](http://flowtype.org/) work with Create React App projects out of the box. 652 | 653 | To add Flow to a Create React App project, follow these steps: 654 | 655 | 1. Run `npm install --save flow-bin` (or `yarn add flow-bin`). 656 | 2. Add `"flow": "flow"` to the `scripts` section of your `package.json`. 657 | 3. Run `npm run flow init` (or `yarn flow init`) to create a [`.flowconfig` file](https://flowtype.org/docs/advanced-configuration.html) in the root directory. 658 | 4. Add `// @flow` to any files you want to type check (for example, to `src/App.js`). 659 | 660 | Now you can run `npm run flow` (or `yarn flow`) to check the files for type errors. 661 | You can optionally use an IDE like [Nuclide](https://nuclide.io/docs/languages/flow/) for a better integrated experience. 662 | In the future we plan to integrate it into Create React App even more closely. 663 | 664 | To learn more about Flow, check out [its documentation](https://flowtype.org/). 665 | 666 | ## Adding Custom Environment Variables 667 | 668 | >Note: this feature is available with `react-scripts@0.2.3` and higher. 669 | 670 | Your project can consume variables declared in your environment as if they were declared locally in your JS files. By 671 | default you will have `NODE_ENV` defined for you, and any other environment variables starting with 672 | `REACT_APP_`. 673 | 674 | **The environment variables are embedded during the build time**. Since Create React App produces a static HTML/CSS/JS bundle, it can’t possibly read them at runtime. To read them at runtime, you would need to load HTML into memory on the server and replace placeholders in runtime, just like [described here](#injecting-data-from-the-server-into-the-page). Alternatively you can rebuild the app on the server anytime you change them. 675 | 676 | >Note: You must create custom environment variables beginning with `REACT_APP_`. Any other variables except `NODE_ENV` will be ignored to avoid accidentally [exposing a private key on the machine that could have the same name](https://github.com/facebookincubator/create-react-app/issues/865#issuecomment-252199527). Changing any environment variables will require you to restart the development server if it is running. 677 | 678 | These environment variables will be defined for you on `process.env`. For example, having an environment 679 | variable named `REACT_APP_SECRET_CODE` will be exposed in your JS as `process.env.REACT_APP_SECRET_CODE`. 680 | 681 | There is also a special built-in environment variable called `NODE_ENV`. You can read it from `process.env.NODE_ENV`. When you run `npm start`, it is always equal to `'development'`, when you run `npm test` it is always equal to `'test'`, and when you run `npm run build` to make a production bundle, it is always equal to `'production'`. **You cannot override `NODE_ENV` manually.** This prevents developers from accidentally deploying a slow development build to production. 682 | 683 | These environment variables can be useful for displaying information conditionally based on where the project is 684 | deployed or consuming sensitive data that lives outside of version control. 685 | 686 | First, you need to have environment variables defined. For example, let’s say you wanted to consume a secret defined 687 | in the environment inside a `<form>`: 688 | 689 | ```jsx 690 | render() { 691 | return ( 692 | <div> 693 | <small>You are running this application in <b>{process.env.NODE_ENV}</b> mode.</small> 694 | <form> 695 | <input type="hidden" defaultValue={process.env.REACT_APP_SECRET_CODE} /> 696 | </form> 697 | </div> 698 | ); 699 | } 700 | ``` 701 | 702 | During the build, `process.env.REACT_APP_SECRET_CODE` will be replaced with the current value of the `REACT_APP_SECRET_CODE` environment variable. Remember that the `NODE_ENV` variable will be set for you automatically. 703 | 704 | When you load the app in the browser and inspect the `<input>`, you will see its value set to `abcdef`, and the bold text will show the environment provided when using `npm start`: 705 | 706 | ```html 707 | <div> 708 | <small>You are running this application in <b>development</b> mode.</small> 709 | <form> 710 | <input type="hidden" value="abcdef" /> 711 | </form> 712 | </div> 713 | ``` 714 | 715 | The above form is looking for a variable called `REACT_APP_SECRET_CODE` from the environment. In order to consume this 716 | value, we need to have it defined in the environment. This can be done using two ways: either in your shell or in 717 | a `.env` file. Both of these ways are described in the next few sections. 718 | 719 | Having access to the `NODE_ENV` is also useful for performing actions conditionally: 720 | 721 | ```js 722 | if (process.env.NODE_ENV !== 'production') { 723 | analytics.disable(); 724 | } 725 | ``` 726 | 727 | When you compile the app with `npm run build`, the minification step will strip out this condition, and the resulting bundle will be smaller. 728 | 729 | ### Referencing Environment Variables in the HTML 730 | 731 | >Note: this feature is available with `react-scripts@0.9.0` and higher. 732 | 733 | You can also access the environment variables starting with `REACT_APP_` in the `public/index.html`. For example: 734 | 735 | ```html 736 | <title>%REACT_APP_WEBSITE_NAME% 737 | ``` 738 | 739 | Note that the caveats from the above section apply: 740 | 741 | * Apart from a few built-in variables (`NODE_ENV` and `PUBLIC_URL`), variable names must start with `REACT_APP_` to work. 742 | * The environment variables are injected at build time. If you need to inject them at runtime, [follow this approach instead](#generating-dynamic-meta-tags-on-the-server). 743 | 744 | ### Adding Temporary Environment Variables In Your Shell 745 | 746 | Defining environment variables can vary between OSes. It’s also important to know that this manner is temporary for the 747 | life of the shell session. 748 | 749 | #### Windows (cmd.exe) 750 | 751 | ```cmd 752 | set REACT_APP_SECRET_CODE=abcdef&&npm start 753 | ``` 754 | 755 | (Note: the lack of whitespace is intentional.) 756 | 757 | #### Linux, macOS (Bash) 758 | 759 | ```bash 760 | REACT_APP_SECRET_CODE=abcdef npm start 761 | ``` 762 | 763 | ### Adding Development Environment Variables In `.env` 764 | 765 | >Note: this feature is available with `react-scripts@0.5.0` and higher. 766 | 767 | To define permanent environment variables, create a file called `.env` in the root of your project: 768 | 769 | ``` 770 | REACT_APP_SECRET_CODE=abcdef 771 | ``` 772 | 773 | `.env` files **should be** checked into source control (with the exclusion of `.env*.local`). 774 | 775 | #### What other `.env` files are can be used? 776 | 777 | >Note: this feature is **available with `react-scripts@1.0.0` and higher**. 778 | 779 | * `.env`: Default. 780 | * `.env.local`: Local overrides. **This file is loaded for all environments except test.** 781 | * `.env.development`, `.env.test`, `.env.production`: Environment-specific settings. 782 | * `.env.development.local`, `.env.test.local`, `.env.production.local`: Local overrides of environment-specific settings. 783 | 784 | Files on the left have more priority than files on the right: 785 | 786 | * `npm start`: `.env.development.local`, `.env.development`, `.env.local`, `.env` 787 | * `npm run build`: `.env.production.local`, `.env.production`, `.env.local`, `.env` 788 | * `npm test`: `.env.test.local`, `.env.test`, `.env` (note `.env.local` is missing) 789 | 790 | These variables will act as the defaults if the machine does not explicitly set them.
791 | Please refer to the [dotenv documentation](https://github.com/motdotla/dotenv) for more details. 792 | 793 | >Note: If you are defining environment variables for development, your CI and/or hosting platform will most likely need 794 | these defined as well. Consult their documentation how to do this. For example, see the documentation for [Travis CI](https://docs.travis-ci.com/user/environment-variables/) or [Heroku](https://devcenter.heroku.com/articles/config-vars). 795 | 796 | ## Can I Use Decorators? 797 | 798 | Many popular libraries use [decorators](https://medium.com/google-developers/exploring-es7-decorators-76ecb65fb841) in their documentation.
799 | Create React App doesn’t support decorator syntax at the moment because: 800 | 801 | * It is an experimental proposal and is subject to change. 802 | * The current specification version is not officially supported by Babel. 803 | * If the specification changes, we won’t be able to write a codemod because we don’t use them internally at Facebook. 804 | 805 | However in many cases you can rewrite decorator-based code without decorators just as fine.
806 | Please refer to these two threads for reference: 807 | 808 | * [#214](https://github.com/facebookincubator/create-react-app/issues/214) 809 | * [#411](https://github.com/facebookincubator/create-react-app/issues/411) 810 | 811 | Create React App will add decorator support when the specification advances to a stable stage. 812 | 813 | ## Integrating with an API Backend 814 | 815 | These tutorials will help you to integrate your app with an API backend running on another port, 816 | using `fetch()` to access it. 817 | 818 | ### Node 819 | Check out [this tutorial](https://www.fullstackreact.com/articles/using-create-react-app-with-a-server/). 820 | You can find the companion GitHub repository [here](https://github.com/fullstackreact/food-lookup-demo). 821 | 822 | ### Ruby on Rails 823 | 824 | Check out [this tutorial](https://www.fullstackreact.com/articles/how-to-get-create-react-app-to-work-with-your-rails-api/). 825 | You can find the companion GitHub repository [here](https://github.com/fullstackreact/food-lookup-demo-rails). 826 | 827 | ## Proxying API Requests in Development 828 | 829 | >Note: this feature is available with `react-scripts@0.2.3` and higher. 830 | 831 | People often serve the front-end React app from the same host and port as their backend implementation.
832 | For example, a production setup might look like this after the app is deployed: 833 | 834 | ``` 835 | / - static server returns index.html with React app 836 | /todos - static server returns index.html with React app 837 | /api/todos - server handles any /api/* requests using the backend implementation 838 | ``` 839 | 840 | Such setup is **not** required. However, if you **do** have a setup like this, it is convenient to write requests like `fetch('/api/todos')` without worrying about redirecting them to another host or port during development. 841 | 842 | To tell the development server to proxy any unknown requests to your API server in development, add a `proxy` field to your `package.json`, for example: 843 | 844 | ```js 845 | "proxy": "http://localhost:4000", 846 | ``` 847 | 848 | This way, when you `fetch('/api/todos')` in development, the development server will recognize that it’s not a static asset, and will proxy your request to `http://localhost:4000/api/todos` as a fallback. The development server will only attempt to send requests without a `text/html` accept header to the proxy. 849 | 850 | Conveniently, this avoids [CORS issues](http://stackoverflow.com/questions/21854516/understanding-ajax-cors-and-security-considerations) and error messages like this in development: 851 | 852 | ``` 853 | Fetch API cannot load http://localhost:4000/api/todos. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. 854 | ``` 855 | 856 | Keep in mind that `proxy` only has effect in development (with `npm start`), and it is up to you to ensure that URLs like `/api/todos` point to the right thing in production. You don’t have to use the `/api` prefix. Any unrecognized request without a `text/html` accept header will be redirected to the specified `proxy`. 857 | 858 | The `proxy` option supports HTTP, HTTPS and WebSocket connections.
859 | If the `proxy` option is **not** flexible enough for you, alternatively you can: 860 | 861 | * [Configure the proxy yourself](#configuring-the-proxy-manually) 862 | * Enable CORS on your server ([here’s how to do it for Express](http://enable-cors.org/server_expressjs.html)). 863 | * Use [environment variables](#adding-custom-environment-variables) to inject the right server host and port into your app. 864 | 865 | ### "Invalid Host Header" Errors After Configuring Proxy 866 | 867 | When you enable the `proxy` option, you opt into a more strict set of host checks. This is necessary because leaving the backend open to remote hosts makes your computer vulnerable to DNS rebinding attacks. The issue is explained in [this article](https://medium.com/webpack/webpack-dev-server-middleware-security-issues-1489d950874a) and [this issue](https://github.com/webpack/webpack-dev-server/issues/887). 868 | 869 | This shouldn’t affect you when developing on `localhost`, but if you develop remotely like [described here](https://github.com/facebookincubator/create-react-app/issues/2271), you will see this error in the browser after enabling the `proxy` option: 870 | 871 | >Invalid Host header 872 | 873 | To work around it, you can specify your public development host in a file called `.env.development` in the root of your project: 874 | 875 | ``` 876 | HOST=mypublicdevhost.com 877 | ``` 878 | 879 | If you restart the development server now and load the app from the specified host, it should work. 880 | 881 | If you are still having issues or if you’re using a more exotic environment like a cloud editor, you can bypass the host check completely by adding a line to `.env.development.local`. **Note that this is dangerous and exposes your machine to remote code execution from malicious websites:** 882 | 883 | ``` 884 | # NOTE: THIS IS DANGEROUS! 885 | # It exposes your machine to attacks from the websites you visit. 886 | DANGEROUSLY_DISABLE_HOST_CHECK=true 887 | ``` 888 | 889 | We don’t recommend this approach. 890 | 891 | ### Configuring the Proxy Manually 892 | 893 | >Note: this feature is available with `react-scripts@1.0.0` and higher. 894 | 895 | If the `proxy` option is **not** flexible enough for you, you can specify an object in the following form (in `package.json`).
896 | You may also specify any configuration value [`http-proxy-middleware`](https://github.com/chimurai/http-proxy-middleware#options) or [`http-proxy`](https://github.com/nodejitsu/node-http-proxy#options) supports. 897 | ```js 898 | { 899 | // ... 900 | "proxy": { 901 | "/api": { 902 | "target": "", 903 | "ws": true 904 | // ... 905 | } 906 | } 907 | // ... 908 | } 909 | ``` 910 | 911 | All requests matching this path will be proxies, no exceptions. This includes requests for `text/html`, which the standard `proxy` option does not proxy. 912 | 913 | If you need to specify multiple proxies, you may do so by specifying additional entries. 914 | You may also narrow down matches using `*` and/or `**`, to match the path exactly or any subpath. 915 | ```js 916 | { 917 | // ... 918 | "proxy": { 919 | // Matches any request starting with /api 920 | "/api": { 921 | "target": "", 922 | "ws": true 923 | // ... 924 | }, 925 | // Matches any request starting with /foo 926 | "/foo": { 927 | "target": "", 928 | "ssl": true, 929 | "pathRewrite": { 930 | "^/foo": "/foo/beta" 931 | } 932 | // ... 933 | }, 934 | // Matches /bar/abc.html but not /bar/sub/def.html 935 | "/bar/*.html": { 936 | "target": "", 937 | // ... 938 | }, 939 | // Matches /baz/abc.html and /baz/sub/def.html 940 | "/baz/**/*.html": { 941 | "target": "" 942 | // ... 943 | } 944 | } 945 | // ... 946 | } 947 | ``` 948 | 949 | ### Configuring a WebSocket Proxy 950 | 951 | When setting up a WebSocket proxy, there are a some extra considerations to be aware of. 952 | 953 | If you’re using a WebSocket engine like [Socket.io](https://socket.io/), you must have a Socket.io server running that you can use as the proxy target. Socket.io will not work with a standard WebSocket server. Specifically, don't expect Socket.io to work with [the websocket.org echo test](http://websocket.org/echo.html). 954 | 955 | There’s some good documentation available for [setting up a Socket.io server](https://socket.io/docs/). 956 | 957 | Standard WebSockets **will** work with a standard WebSocket server as well as the websocket.org echo test. You can use libraries like [ws](https://github.com/websockets/ws) for the server, with [native WebSockets in the browser](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket). 958 | 959 | Either way, you can proxy WebSocket requests manually in `package.json`: 960 | 961 | ```js 962 | { 963 | // ... 964 | "proxy": { 965 | "/socket": { 966 | // Your compatible WebSocket server 967 | "target": "ws://", 968 | // Tell http-proxy-middleware that this is a WebSocket proxy. 969 | // Also allows you to proxy WebSocket requests without an additional HTTP request 970 | // https://github.com/chimurai/http-proxy-middleware#external-websocket-upgrade 971 | "ws": true 972 | // ... 973 | } 974 | } 975 | // ... 976 | } 977 | ``` 978 | 979 | ## Using HTTPS in Development 980 | 981 | >Note: this feature is available with `react-scripts@0.4.0` and higher. 982 | 983 | You may require the dev server to serve pages over HTTPS. One particular case where this could be useful is when using [the "proxy" feature](#proxying-api-requests-in-development) to proxy requests to an API server when that API server is itself serving HTTPS. 984 | 985 | To do this, set the `HTTPS` environment variable to `true`, then start the dev server as usual with `npm start`: 986 | 987 | #### Windows (cmd.exe) 988 | 989 | ```cmd 990 | set HTTPS=true&&npm start 991 | ``` 992 | 993 | (Note: the lack of whitespace is intentional.) 994 | 995 | #### Linux, macOS (Bash) 996 | 997 | ```bash 998 | HTTPS=true npm start 999 | ``` 1000 | 1001 | Note that the server will use a self-signed certificate, so your web browser will almost definitely display a warning upon accessing the page. 1002 | 1003 | ## Generating Dynamic `` Tags on the Server 1004 | 1005 | Since Create React App doesn’t support server rendering, you might be wondering how to make `` tags dynamic and reflect the current URL. To solve this, we recommend to add placeholders into the HTML, like this: 1006 | 1007 | ```html 1008 | 1009 | 1010 | 1011 | 1012 | 1013 | ``` 1014 | 1015 | Then, on the server, regardless of the backend you use, you can read `index.html` into memory and replace `__OG_TITLE__`, `__OG_DESCRIPTION__`, and any other placeholders with values depending on the current URL. Just make sure to sanitize and escape the interpolated values so that they are safe to embed into HTML! 1016 | 1017 | If you use a Node server, you can even share the route matching logic between the client and the server. However duplicating it also works fine in simple cases. 1018 | 1019 | ## Pre-Rendering into Static HTML Files 1020 | 1021 | If you’re hosting your `build` with a static hosting provider you can use [react-snapshot](https://www.npmjs.com/package/react-snapshot) to generate HTML pages for each route, or relative link, in your application. These pages will then seamlessly become active, or “hydrated”, when the JavaScript bundle has loaded. 1022 | 1023 | There are also opportunities to use this outside of static hosting, to take the pressure off the server when generating and caching routes. 1024 | 1025 | The primary benefit of pre-rendering is that you get the core content of each page _with_ the HTML payload—regardless of whether or not your JavaScript bundle successfully downloads. It also increases the likelihood that each route of your application will be picked up by search engines. 1026 | 1027 | You can read more about [zero-configuration pre-rendering (also called snapshotting) here](https://medium.com/superhighfives/an-almost-static-stack-6df0a2791319). 1028 | 1029 | ## Injecting Data from the Server into the Page 1030 | 1031 | Similarly to the previous section, you can leave some placeholders in the HTML that inject global variables, for example: 1032 | 1033 | ```js 1034 | 1035 | 1036 | 1037 | 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 | ![Jest watch mode](http://facebook.github.io/jest/img/blog/15-watch.gif) 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 ` 85 | 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 | } --------------------------------------------------------------------------------