├── .babelrc
├── .eslintrc.js
├── .github
├── CONTRIBUTING.md
├── ISSUE_TEMPLATE.md
└── PULL_REQUEST_TEMPLATE.md
├── .gitignore
├── .npmignore
├── .travis.yml
├── .vscode
└── settings.json
├── CHANGELOG.md
├── LICENSE.txt
├── README.md
├── config
├── env.js
├── jest
│ ├── cssTransform.js
│ └── fileTransform.js
├── modules.js
├── paths.js
├── pnpTs.js
├── webpack.config.build.js
├── webpack.config.js
└── webpackDevServer.config.js
├── contribute-home.md
├── css
└── react-datetime.css
├── dist
├── react-datetime.cjs.js
├── react-datetime.cjs.js.map
├── react-datetime.umd.js
└── react-datetime.umd.js.map
├── migrateToV3.md
├── package.json
├── public
└── index.html
├── react-datetime.d.ts
├── resources.md
├── scripts
├── build.js
├── start.js
└── test.js
├── src
├── DateTime.js
├── parts
│ └── ViewNavigation.js
├── playground
│ ├── App.js
│ └── index.js
└── views
│ ├── DaysView.js
│ ├── MonthsView.js
│ ├── TimeView.js
│ └── YearsView.js
├── test
├── __snapshots__
│ └── snapshots.spec.js.snap
├── snapshots.spec.js
├── testUtils.js
├── tests.spec.js
└── viewDate.spec.js
└── typings
├── DateTime.d.ts
├── react-datetime-tests.tsx
└── tsconfig.json
/.babelrc:
--------------------------------------------------------------------------------
1 | {
2 | "presets": [
3 | "@babel/preset-react",
4 | "@babel/preset-env"
5 | ],
6 | "plugins": [
7 | "@babel/plugin-proposal-class-properties"
8 | ]
9 | }
--------------------------------------------------------------------------------
/.eslintrc.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | "env": {
3 | "es6": true,
4 | "browser": true
5 | },
6 | "globals": {
7 | "require": true,
8 | "module": true
9 | },
10 | // Enables rules that report common problems,
11 | // see http://eslint.org/docs/rules/ for list
12 | "extends": "eslint:recommended",
13 | "rules": {
14 | // Enforce the use of variables within the scope they are defined
15 | "block-scoped-var": 2,
16 | // Enforce camelcase naming convention
17 | "camelcase": 2,
18 | // Enforce consistent spacing before and after commas
19 | "comma-spacing": 2,
20 | // Enforce at least one newline at the end of files
21 | "eol-last": 2,
22 | // Require the use of === and !==
23 | "eqeqeq": [2, "smart"],
24 | // Enforce consistent spacing before and after keywords
25 | "keyword-spacing": [2, { "before": true, "after": true }],
26 | // Disallow multiple empty lines
27 | "no-multiple-empty-lines": [2, { "max": 1, "maxEOF": 1, "maxBOF": 0 }],
28 | // Enforce the consistent use of the radix argument when using parseInt()
29 | "radix": 2,
30 | // Require or disallow semicolons instead of AS
31 | "semi": 2,
32 | // Enforce consistent spacing before and after semicolons
33 | "semi-spacing": 2,
34 | // Enforce consistent spacing before blocks
35 | "space-before-blocks": 2,
36 | // Enforce consistent spacing inside parentheses
37 | // "space-in-parens": [2, "always"],
38 | // Enforce the consistent use of either backticks, double, or single quotes
39 | "quotes": [2, "single", { "avoidEscape": true, "allowTemplateLiterals": true }],
40 | // Enforce using tabs for indentation
41 | "indent": [2, "tab", { "SwitchCase": 1 }]
42 | },
43 | "parserOptions": {
44 | "sourceType": "module"
45 | },
46 | "extends": "react-app"
47 | };
48 |
--------------------------------------------------------------------------------
/.github/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing
2 | :raised_hands::tada: First off, thanks for taking the time to contribute! :tada::raised_hands:
3 |
4 | The following is a set of guidelines for contributing to react-datetime. The purpose of these
5 | guidelines is to maintain a high quality of code *and* traceability. Please respect these
6 | guidelines.
7 |
8 | ## General
9 | This repository use tests and a linter as automatic tools to maintain the quality of the code.
10 | These two tasks are run locally on your machine before every commit (as a pre-commit git hook),
11 | if any test fail or the linter gives an error the commit will not be created. They are also run on
12 | a Travis CI machine when you create a pull request, and the PR will not be merged unless Travis
13 | says all tests and the linting pass.
14 |
15 | ## Git Commit Messages
16 | * Use the present tense ("Add feature" not "Added feature")
17 | * Use the imperative mood ("Move cursor to..." not "Moves cursor to...")
18 | * Think of it as you are *commanding* what your commit is doing
19 | * Git itself uses the imperative whenever it creates a commit on your behalf, so it makes sense
20 | for you to use it too
21 | * Use the body to explain *what* and *why*
22 | * If the commit is non-trivial, please provide more detailed information in the commit body
23 | message
24 | * *How* you made the change is visible in the code and is therefore rarely necessary to include
25 | in the commit body message, but *why* you made the change is often harder to guess and is
26 | therefore useful to include in the commit body message
27 |
28 | [Here's a nice blog post on how to write great git messages.](http://chris.beams.io/posts/git-commit/)
29 |
30 | ## Pull Requests
31 | * Follow the current code style
32 | * Write tests for your changes
33 | * Document your changes in the README if it's needed
34 | * End files with a newline
35 | * There's no need to create a new build for each pull request, we (the maintainers) do this when we
36 | release a new version
37 |
38 | ## Issues
39 | * Please be descriptive when you fill in the issue template, this will greatly help us maintainers
40 | in helping you which will lead to your issue being resolved faster
41 | * Feature requests are very welcomed, but not every feature that is requested can be guaranteed
42 | to be implemented
43 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE.md:
--------------------------------------------------------------------------------
1 |
25 |
26 |
27 | ### I'm Submitting a ...
28 |
29 | ```
30 | [ ] Bug report
31 | [ ] Feature request
32 | [ ] Support request
33 | ```
34 |
35 | ### Steps to Reproduce
36 |
37 |
38 | ### Expected Results
39 |
40 |
41 | ### Actual Results
42 |
43 |
44 | ### Minimal Reproduction of the Problem
45 |
52 |
53 | ### Other Information (e.g. stacktraces, related issues, suggestions how to fix)
54 |
55 |
56 |
57 |
61 |
--------------------------------------------------------------------------------
/.github/PULL_REQUEST_TEMPLATE.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | ### Description
4 |
5 |
6 | ### Motivation and Context
7 |
12 |
13 | ### Checklist
14 |
20 | ```
21 | [ ] I have not included any built dist files (us maintainers do that prior to a new release)
22 | [ ] I have added tests covering my changes
23 | [ ] All new and existing tests pass
24 | [ ] My changes required the documentation to be updated
25 | [ ] I have updated the documentation accordingly
26 | [ ] I have updated the TypeScript 1.8 type definitions accordingly
27 | [ ] I have updated the TypeScript 2.0+ type definitions accordingly
28 | ```
29 |
30 |
31 |
35 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *~
2 | node_modules
3 | .idea
4 | tmp
5 | .DS_Store
6 | npm-debug.log
7 |
8 | # Don't force sha validation (it differs depending on the OS)
9 | package-lock.json
--------------------------------------------------------------------------------
/.npmignore:
--------------------------------------------------------------------------------
1 | # Folders
2 | node_modules
3 | example
4 | .idea
5 | test
6 |
7 | # Files
8 | *~
9 | .DS_Store
10 | npm-debug.log
11 | webpack.config.js
12 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: node_js
2 | sudo: false
3 | os:
4 | - linux
5 | node_js:
6 | - '8'
7 | - 'stable'
8 | script:
9 | - npm run lint
10 | - npm run test:all
11 | before_install:
12 | - export TZ=Europe/Stockholm
13 | notifications:
14 | email: false
15 |
--------------------------------------------------------------------------------
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "editor.codeActionsOnSave": {
3 | "source.fixAll.eslint": true
4 | }
5 | }
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | Changelog
2 | =========
3 | ## 3.3.1
4 | * Restores compatibility with React ^16.5.0
5 |
6 | ## 3.3.0
7 | * Adds support for React 19
8 |
9 | ## 3.2.0
10 | * Adds support for React 18
11 |
12 | ## 3.1.0
13 | * Adds support for React 17
14 |
15 | ## 3.0.3
16 | * Localize AM and PM strings
17 | * Make calendar fluid width
18 | * Fixes findDOMNode deprecated warning in Strict Mode - Thanks @kkalve
19 | * Simplification of the base code - Thanks @onlined
20 |
21 | ## 3.0.2
22 | * Fixes typescript typings not being exposed publicly
23 |
24 | ## 3.0.1
25 | * Big refactor, the state is not derived from the props after every update.
26 | * `disableCloseOnClickOutside` prop is now `closeOnClickOutside` (avoid double negations).
27 | * `onBlur` and `onFocus` are renamed to `onClose` and `onOpen` since they had nothing to do with the blur event and it was misleading some users. If we want to listen to the input's `onBlur` and `onFocus` use `inputProps`.
28 | * `defaultValue` prop is now called `initialValue`.
29 | * Updated typescript definitions.
30 | * Time is not updated anymore on right clicks.
31 | * Creates `renderView` prop to customize the whole calendar.
32 | * Creates `updateOnView` prop to decide when to update the date.
33 | * `onViewModeChange` prop renamed to `onNavigate`.
34 | * Creates `onBeforeNavigate` prop.
35 | * Creates `setViewData` and `navigate` methods.
36 | * Fixes error clicking on days from the previous or next month in the days view.
37 | * Fixes month, year and time views for locales that doesn't use gregorian numbers.
38 | * Adds a playground to make simpler to try out the library by `npm run playground`.
39 | * Not depending on gulp to create the build anymore
40 | * Updated most of the dependencies.
41 |
42 | ## 3.0.0
43 | - This version was published by error and can't be overriden. The first release for v3 branch is 3.0.1
44 |
45 | ## 2.16.2
46 | * Turns moment timezone peer dependency in a runtime error when missing using `displayTimezone`.
47 |
48 | ## 2.16.1
49 | * Fixes input event overriding
50 |
51 | ## 2.16.0
52 | * The prop `disableOnClickOutside` has been renamed to `disableCloseOnClickOutside`
53 | * The calendar doesn't get closed an open when clicking in the input anymore.
54 | * Fixes errors not finding dates when customizing day rendering.
55 | * Event listeners in `inputProps` now only override default behaviour when returning `false`.
56 | * Adds the `displayTimeZone` prop. Thanks to @martingordon
57 |
58 | ## 2.15.0
59 | * New `onNavigateBack` and `onNavigateForward` hooks thanks to @DaanDD and @simeg.
60 | * Touch improvements by @NicoDos
61 | * TS and debugging improvements
62 |
63 | ## 2.14.0
64 | * Make `viewDate` dynamic
65 |
66 | ## 2.13.0
67 | * Use more appropriate cursor for empty space in time picker and in day texts
68 | * Add `viewDate` prop that sets a value when opening the calendar when there is no selected date
69 | * Make `disableOnClickOutside` work as intended
70 | * Better touch support for tapping and holding
71 | * Use static property `defaultProps` instead of `getDefaultProps`
72 |
73 | ## 2.12.0
74 | * The `renderInput` prop now receives `closeCalendar` function as well
75 |
76 | ## 2.11.1
77 | * The open prop should now work as intended
78 |
79 | ## 2.11.0
80 | * onFocus now receives the browser event
81 | * Do not open browser menu on right click of arrows in time view
82 | * Open calendar when onClick is triggered, before it would just react to onFocus
83 | * Update TypeScript definitions for value and defaultValue to comply with code
84 | * Fix bug where AM/PM would not sync between component value and input field value
85 | * Add renderInput prop which let's the consumer of the component render their own HTML input element
86 |
87 | ## 2.10.3
88 | * Update react-onclickoutside dependency
89 | * Remove isValidDate check before rendering as implementation was causing crashes in some edge cases.
90 |
91 | ## 2.10.2
92 | * Move @types/react back to devDependencies
93 | * Add [demo](https://codesandbox.io/s/boring-dew-uzln3) app.
94 |
95 | ## 2.10.1
96 | * Fix build files.
97 |
98 | ## 2.10.0
99 | * Add isValidDate check before rendering so it doesn't render with an invalid date.
100 |
101 | ## 2.9.0
102 | * Trigger callback method on view mode changes
103 |
104 | ## 2.8.11
105 | * Update TypeScript definitions
106 | * Replace deprecated React method with non-deprecated method
107 |
108 | ## 2.8.10
109 | * Increase click area of arrows for changing day/month/year
110 | * Update code according to React 15.5.0
111 | * Remove usage of React.createClass
112 | * Use separate module for PropTypes
113 |
114 | ## 2.8.9
115 | * Fixes issue where incorrect current month is shown
116 |
117 | ## 2.8.8
118 | * Fixes issues introduced in v2.8.7 recognizing any calendar view as clickingOutside trigger
119 |
120 | ## 2.8.7
121 | * Update react-onclickoutside dependency. That should fix most of the problems about closeOnSelect.
122 |
123 | ## 2.8.6
124 | * Revert commits related to `closeOnSelect` that did not fix all issues they were meant to
125 |
126 | ## 2.8.5
127 | * Fix bug where `closeOnSelect` was not closing when it was set to `true`
128 | * Fix bug where component would not immediately re-render when updating either `utc` or `locale` prop
129 |
130 | ## 2.8.4
131 | * Fix bug where `closeOnSelect=true` would cause component to close on state change
132 |
133 | ## 2.8.3
134 | * Fix `isValidDate` related bug where current month would be invalid
135 | * Trigger re-render of component when `viewMode` changes
136 | * Never append `rdtOld` class in year view
137 |
138 | ## 2.8.2
139 | * Fix year related bug in tests where year was set to 2016
140 | * Add a yarnfile so yarn is now possible to use for installing dependencies
141 |
142 | ## 2.8.1
143 | * Fix timeFormat related bug where 'A' was being picked up but not 'a', for setting 12-hour clock.
144 |
145 | ## 2.8.0
146 | * Add typings for TypeScript 2.0. We now support TypeScript typings for versions 1.8 and 2.0.
147 |
148 | ## 2.7.5
149 | * Bumps the version to skip buggy deployment 2.7.4
150 |
151 | ## 2.7.4
152 | * Reverting updating `react` related dependencies. They were not the issue so they should not be set to the latest version of `react`.
153 |
154 | ## 2.7.3
155 | * When updating `moment` to `2.16.0` something broke, hopefully by updating all `react` prefixed dependencies to `15.4.0` and changing the syntax in the dependency object a bit will resolve this issue.
156 |
157 | ## 2.7.2
158 | * Bug fix: When setting `locale` and entering month view mode the component would sometimes freeze, depending on the locale. This has now been fixed.
159 |
160 | ## 2.7.1
161 | * Bug fix: `onFocus` and `onBlur` were being called in a way causing state to reset. This unwanted behavior is now adjusted.
162 |
163 | ## 2.7.0
164 | * `isValidDate` now supports months and years.
165 | * `utc` prop was added, by setting it to `true` input time values will be interpreted as UTC (Zulu time).
166 | * Bug fix: The input value now updates when `dateFormat` changes.
167 | * Removed the source-map file because the commit it was introduced in was causing the minified file to be bigger than the non-minified.
168 |
169 | ## 2.6.2
170 | * Update file references in `package.json`
171 |
172 | ## 2.6.1
173 | * Added a source-map file.
174 | * Fixed bug with invalid moment object.
175 | * Decreased npm package size by ~29.3KB.
176 |
177 | ## 2.6.0
178 | * Fixed hover styles for days
179 | * Added multiple simultaneous datetime component support.
180 | * `className` prop now supports string arrays
181 | * Fixes 12:00am
182 | * Removed warning for missing element keys.
183 |
184 | ## 2.5.0
185 | * Added pre-commit hook for tests.
186 | * Added the `timeConstraints` prop.
187 |
188 | ## 2.4.0
189 | * Added ES linting.
190 | * Added `closeOnTab` property.
191 |
192 | ## 2.3.3
193 | * Updated readme.
194 | * Fixed short months for not English locales.
195 | * Fixed mixed 12 AM/PM.
196 |
197 | ## 2.3.2
198 | * Time editor now handles the A format to display 12h times.
199 |
200 | ## 2.3.0
201 | * Added typescript definition file.
202 | * Changed button markup and updated styles.
203 | * Fixes autoclosing on time change.
204 |
205 | ## 2.2.1
206 | * Controlled datepicker now working for controlled datepickers
207 |
208 | ## 2.2.0
209 | * The picker can be used as a month or year picker just giving a format date without days/months
210 | * Updates test suite
211 |
212 | ## 2.1.0
213 | * Fixed rdtActive not getting set.
214 | * Add react-dom as external dependency.
215 | * Fixed rendering a span directly under the calendar table.
216 | * Added dev setup
217 | * Added example
218 |
219 | ## 2.0.2
220 | * Fixed january days go to november problem.
221 |
222 | ## 2.0.1
223 | * Fixed two days can't have the same header name.
224 |
225 | ## 2.0.0
226 | * DOM classes are now prefixed with `rdt`.
227 | * A modified version of OnClickOutside is now included in the code to handle react 0.13 and 0.14 versions.
228 | * Updated dependencies.
229 |
230 | ## 1.3.0
231 | * Added open prop.
232 | * Added strictParsing prop.
233 | * Fixed not possible to set value to `''`.
234 |
235 | ## 1.2.1
236 | * Removed classlist-polyfill so the component can be used in the server side.
237 |
238 | ## 1.1.1
239 | * Updates react-onclickoutside dependency to avoid the bug https://github.com/Pomax/react-onclickoutside/issues/20
240 |
241 | ## 1.1.0
242 | * Datepicker can have an empty value. If the value in the input is not valid, `onChange` and `onBlur` will return input value.
243 | * `onBlur` is not triggered anymore if the calendar is not open.
244 |
245 | ## 1.0.0-rc.2
246 | * Added travis CI
247 | * Fixed not showing timepicker when `dateFormat`=`false`.
248 |
249 | ## 1.0.0-rc.1
250 | This is the release candidate for this project. Now it is pretty usable and API won't change drastically in a while. If you were using the alpha versions (v0.x) there is a bunch of breaking changes:
251 |
252 | * `date` prop is now called `defaultValue` and it is the initial value to use the component uncontrolled.
253 | * `value` prop has been added to use it as a [controlled component](https://facebook.github.io/react/docs/forms.html#controlled-components).
254 | * Removed `minDate` and `maxDate` props. Now to define what dates are valid it is possible to use the new `isValidDate` prop.
255 | * `dateFormat` and `timeFormat` default value is always the locale default format. In case that you don't want the component to show the date/time picker you should set `dateFormat`/`timeFormat` to `false`.
256 |
257 | Moreover:
258 | * Buttons doesn't submit anymore when the Datetime component is in a form.
259 | * `className` prop has been added to customize component class.
260 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) Javier Marquez
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 NON INFRINGEMENT. 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.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # react-datetime
2 |
3 | [](https://travis-ci.org/arqex/react-datetime)
4 | [](http://badge.fury.io/js/react-datetime)
5 |
6 | A date and time picker in the same React.js component. It can be used as a datepicker, timepicker or both at the same time. It is **highly customizable** and it even allows to edit date's milliseconds.
7 |
8 | > **Back to the roots!** Thanks to the people of [YouCanBook.me (best scheduling tool)](https://youcanbook.me) for sponsoring react-datetime for so long. Now the project returns to the community and we are **looking for contributors** to continue improving react-datetime. [Would you like to give a hand?](contribute-home.md)
9 |
10 | **Version 3 is out!** These are the docs for version 3 of the library. If you are still using the deprecated v2, [here it is its documentation](https://github.com/arqex/react-datetime/blob/2a83208452ac5e41c43fea31ef47c65efba0bb56/README.md), but we strongly recommend to migrate to version 3 in order to keep receiving updates. Please check [migrating react-datetime to version 3](migrateToV3.md) to safely update your app.
11 |
12 | ## Installation
13 |
14 | Install using npm:
15 | ```sh
16 | npm install --save react-datetime
17 | ```
18 |
19 | Install using yarn:
20 | ```sh
21 | yarn add react-datetime
22 | ```
23 |
24 | ## Usage
25 |
26 | [React.js](http://facebook.github.io/react/) and [Moment.js](http://momentjs.com/) are peer dependencies for react-datetime (as well as [Moment.js timezones](https://momentjs.com/timezone/) if you want to use the `displayTimeZone` prop). These dependencies are not installed along with react-datetime automatically, but your project needs to have them installed in order to make the datepicker work. You can then use the datepicker like in the example below.
27 |
28 | ```js
29 | // Import the library
30 | import Datetime from 'react-datetime';
31 |
32 | // return it from your components
33 | return ;
34 | ```
35 | [See this example working](https://codesandbox.io/s/boring-dew-uzln3).
36 |
37 | Do you want more examples? [Have a look at our resources gallery](resources.md).
38 |
39 | **Don't forget to add the [CSS stylesheet](https://github.com/arqex/react-datetime/blob/master/css/react-datetime.css) to make it work out of the box.**. You only need to do this once in your app:
40 |
41 | ```js
42 | import "react-datetime/css/react-datetime.css";
43 | ```
44 |
45 | ## API
46 |
47 | Below we have all the props that we can use with the `` component. There are also some methods that can be used imperatively.
48 |
49 | | Name | Type | Default | Description |
50 | | ------------ | ------- | ------- | ----------- |
51 | | **value** | `Date` | `new Date()` | Represents the selected date by the component, in order to use it as a [controlled component](https://facebook.github.io/react/docs/forms.html#controlled-components). This prop is parsed by Moment.js, so it is possible to use a date `string` or a `moment` object. |
52 | | **initialValue** | `Date` | `new Date()` | Represents the selected date for the component to use it as a [uncontrolled component](https://facebook.github.io/react/docs/uncontrolled-components.html). This prop is parsed by Moment.js, so it is possible to use a date `string` or a `moment` object. If you need to set the selected date programmatically after the picker is initialized, please use the `value` prop instead. |
53 | | **initialViewDate** | `Date` | `new Date()` | Define the month/year/decade/time which is viewed on opening the calendar. This prop is parsed by Moment.js, so it is possible to use a date `string` or a `moment` object. If you want to set the view date after the component has been initialize [see the imperative API](#imperative-api). |
54 | | **initialViewMode** | `string` or `number` | `'days'` | The default view to display when the picker is shown for the first time (`'years'`, `'months'`, `'days'`, `'time'`). If you want to set the view mode after the component has been initialize [see the imperative API](#imperative-api). |
55 | | **updateOnView** | `string` | Intelligent guess | By default we can navigate through years and months without actualling updating the selected date. Only when we get to one view called the "updating view", we make a selection there and the value gets updated, triggering an `onChange` event. By default the updating view will get guessed by using the `dateFormat` so if our dates only show months and never days, the update is done in the `months` view. If we set `updateOnView="time"` selecting a day will navigate to the time view. The time view always updates the selected date, never navigates. If `closeOnSelect={ true }`, making a selection in the view defined by `updateOnView` will close the calendar. |
56 | | **dateFormat** | `boolean` or `string` | `true` | Defines the format for the date. It accepts any [Moment.js date format](http://momentjs.com/docs/#/displaying/format/) (not in localized format). If `true` the date will be displayed using the defaults for the current locale. If `false` the datepicker is disabled and the component can be used as timepicker, see [available units docs](#specify-available-units). |
57 | | **timeFormat** | `boolean` or `string` | `true` | Defines the format for the time. It accepts any [Moment.js time format](http://momentjs.com/docs/#/displaying/format/) (not in localized format). If `true` the time will be displayed using the defaults for the current locale. If `false` the timepicker is disabled and the component can be used as datepicker, see [available units docs](#specify-available-units). |
58 | | **input** | `boolean` | `true` | Whether to show an input field to edit the date manually. |
59 | | **open** | `boolean` | `null` | Whether to open or close the picker. If not set react-datetime will open the datepicker on input focus and close it on click outside. |
60 | | **locale** | `string` | `null` | Manually set the locale for the react-datetime instance. Moment.js locale needs to be loaded to be used, see [i18n docs](#i18n).
61 | | **utc** | `boolean` | `false` | When true, input time values will be interpreted as UTC (Zulu time) by Moment.js. Otherwise they will default to the user's local timezone.
62 | | **displayTimeZone** | `string` | `null` | **Needs [moment's timezone](https://momentjs.com/timezone/) available in your project.** When specified, input time values will be displayed in the given time zone. Otherwise they will default to the user's local timezone (unless `utc` specified).
63 | | **onChange** | `function` | empty function | Callback trigger when the date changes. The callback receives the selected `moment` object as only parameter, if the date in the input is valid. If the date in the input is not valid, the callback receives the value of the input (a string). |
64 | | **onOpen** | `function` | empty function | Callback trigger for when the user opens the datepicker. |
65 | | **onClose** | `function` | empty function | Callback trigger for when the calendar get closed. The callback receives the selected `moment` object as only parameter, if the date in the input is valid. If the date in the input is not valid, the callback returns the value in the input. |
66 | | **onNavigate** | `function` | empty function | Callback trigger when the view mode changes. The callback receives the selected view mode string (`years`, `months`, `days` or `time`) as only parameter.|
67 | | **onBeforeNavigate** | `function` | ( nextView, currentView, viewDate ) => nextView | Allows to intercept a change of the calendar view. The accepted function receives the view that it's supposed to navigate to, the view that is showing currently and the date currently shown in the view. Return a viewMode ( default ones are `years`, `months`, `days` or `time`) to navigate to it. If the function returns a "falsy" value, the navigation is stopped and we will remain in the current view. |
68 | | **onNavigateBack** | `function` | empty function | Callback trigger when the user navigates to the previous month, year or decade. The callback receives the amount and type ('month', 'year') as parameters. |
69 | | **onNavigateForward** | `function` | empty function | Callback trigger when the user navigates to the next month, year or decade. The callback receives the amount and type ('month', 'year') as parameters. |
70 | | **className** | `string` or `string array` | `''` | Extra class name for the outermost markup element. |
71 | | **inputProps** | `object` | `undefined` | Defines additional attributes for the input element of the component. For example: `onClick`, `placeholder`, `disabled`, `required`, `name` and `className` (`className` *sets* the class attribute for the input element). See [Customize the Input Appearance](#customize-the-input-appearance). |
72 | | **isValidDate** | `function` | `() => true` | Define the dates that can be selected. The function receives `(currentDate, selectedDate)` and shall return a `true` or `false` whether the `currentDate` is valid or not. See [selectable dates](#selectable-dates).|
73 | | **renderInput** | `function` | `undefined` | Replace the rendering of the input element. The function has the following arguments: the default calculated `props` for the input, `openCalendar` (a function which opens the calendar) and `closeCalendar` (a function which closes the calendar). Must return a React component or `null`. See [Customize the Input Appearance](#customize-the-input-appearance). |
74 | | **renderView** | `function` | `(viewMode, renderDefault) => renderDefault()` | Customize the way the calendar is rendered. The accepted function receives the type of the view it's going to be rendered `'years', 'months', 'days', 'time'` and a function to render the default view of react-datetime, this way it's possible to wrap the original view adding our own markup or override it completely with our own code. See [Customize the Datepicker Appearance](#customize-the-datepicker-appearance). |
75 | | **renderDay** | `function` | `DOM.td(day)` | Customize the way that the days are shown in the daypicker. The accepted function has the `selectedDate`, the current date and the default calculated `props` for the cell, and must return a React component. See [Customize the Datepicker Appearance](#customize-the-datepicker-appearance). |
76 | | **renderMonth** | `function` | `DOM.td(month)` | Customize the way that the months are shown in the monthpicker. The accepted function has the `selectedDate`, the current date and the default calculated `props` for the cell, the `month` and the `year` to be shown, and must return a React component. See [Customize the Datepicker Appearance](#customize-the-datepicker-appearance). |
77 | | **renderYear** | `function` | `DOM.td(year)` | Customize the way that the years are shown in the year picker. The accepted function has the `selectedDate`, the current date and the default calculated `props` for the cell, the `year` to be shown, and must return a React component. See [Customize the Datepicker Appearance](#customize-the-datepicker-appearance). |
78 | | **strictParsing** | `boolean` | `true` | Whether to use Moment.js's [strict parsing](http://momentjs.com/docs/#/parsing/string-format/) when parsing input.
79 | | **closeOnSelect** | `boolean` | `false` | When `true`, once the day has been selected, the datepicker will be automatically closed.
80 | | **closeOnTab** | `boolean` | `true` | When `true` and the input is focused, pressing the `tab` key will close the datepicker.
81 | | **timeConstraints** | `object` | `null` | Add some constraints to the timepicker. It accepts an `object` with the format `{ hours: { min: 9, max: 15, step: 2 }}`, this example means the hours can't be lower than `9` and higher than `15`, and it will change adding or subtracting `2` hours everytime the buttons are clicked. The constraints can be added to the `hours`, `minutes`, `seconds` and `milliseconds`.
82 | | **closeOnClickOutside** | `boolean` | `true` | When the calendar is open and `closeOnClickOutside` is `true` (its default value), clickin outside of the calendar or input closes the calendar. If `false` the calendar stays open.
83 |
84 | ## Imperative API
85 | Besides controlling the selected date, there is a navigation through months, years, decades that react-datetime handles for us. We can interfere in it, stopping view transtions by using the prop `onBeforeNavigate`, but we can also navigate to a specific view and date by using some imperative methods.
86 |
87 | To do so, we need to create our component with a `ref` prop amd use the reference.
88 | ```js
89 | // This would be the code to render the picker
90 |
91 |
92 | // ... once rendered we can use the imperative API
93 | // let's show the years view
94 | this.refs.datetime.navigate('years')
95 | ```
96 |
97 | Available methods are:
98 | * **navigate( viewMode )**: Set the view currently shown by the calendar. View modes shipped with react-datetime are `years`, `months`, `days` and `time`, but you can alse navigate to custom modes that can be defined by using the `renderView` prop.
99 | * **setViewDate( date )**: Set the date that is currently shown in the calendar. This is independent from the selected date and it's the one used to navigate through months or days in the calendar. It accepts a string in the format of the current locale, a `Date` or a `Moment` object as parameter.
100 |
101 | ## i18n
102 | Different language and date formats are supported by react-datetime. React uses [Moment.js](http://momentjs.com/) to format the dates, and the easiest way of changing the language of the calendar is [changing the Moment.js locale](http://momentjs.com/docs/#/i18n/changing-locale/).
103 |
104 | Don't forget to import your locale file from the moment's `moment/locale` folder.
105 |
106 | ```js
107 | import moment from 'moment';
108 | import 'moment/locale/fr';
109 | // Now react-datetime will be in french
110 | ```
111 |
112 | If there are multiple locales loaded, you can use the prop `locale` to define what language shall be used by the instance.
113 | ```js
114 |
115 |
116 | ```
117 | [Here you can see the i18n example working](https://codesandbox.io/s/interesting-kare-0707b).
118 |
119 | ## Customize the Input Appearance
120 | It is possible to customize the way that the input is displayed. The simplest is to supply `inputProps` which will get directly assigned to the `` element within the component. We can tweak the inputs this way:
121 |
122 | ```js
123 | let inputProps = {
124 | placeholder: 'N/A',
125 | disabled: true,
126 | onMouseLeave: () => alert('You went to the input but it was disabled')
127 | };
128 |
129 |
130 | ```
131 | [See the customized input working](https://codesandbox.io/s/clever-wildflower-81r26?file=/src/App.js)
132 |
133 |
134 | Alternatively, if you need to render different content than an `` element, you may supply a `renderInput` function which is called instead.
135 |
136 | ```js
137 | class MyDTPicker extends React.Component {
138 | render(){
139 | return ;
140 | }
141 | renderInput( props, openCalendar, closeCalendar ){
142 | function clear(){
143 | props.onChange({target: {value: ''}});
144 | }
145 | return (
146 |
147 |
148 |
149 |
150 |
151 |
152 | );
153 | }
154 | }
155 | ```
156 |
157 | [See this example working](https://codesandbox.io/s/peaceful-water-3gb5m)
158 |
159 |
160 | Or maybe you just want to shown the calendar and don't need an input at all. In that case `input={ false }` will make the trick:
161 |
162 | ```js
163 | ;
164 | ```
165 | [See react-datetime calendar working without an input](https://codesandbox.io/s/busy-vaughan-wh773)
166 |
167 | ## Customize the Datepicker Appearance
168 | It is possible to customize the way that the datepicker display the days, months and years in the calendar. To adapt the calendar for every need it is possible to use the props `renderDay(props, currentDate, selectedDate)`, `renderMonth(props, month, year, selectedDate)` and `renderYear(props, year, selectedDate)` to customize the output of each rendering method.
169 |
170 | ```js
171 | class MyDTPicker extends React.Component {
172 | render() {
173 | return (
174 |
179 | );
180 | }
181 | renderDay(props, currentDate, selectedDate) {
182 | // Adds 0 to the days in the days view
183 | return
{"0" + currentDate.date()}
;
184 | }
185 | renderMonth(props, month, year, selectedDate) {
186 | // Display the month index in the months view
187 | return
{month}
;
188 | }
189 | renderYear(props, year, selectedDate) {
190 | // Just display the last 2 digits of the year in the years view
191 | return
{year % 100}
;
192 | }
193 | }
194 | ```
195 | [See the customized calendar here.](https://codesandbox.io/s/peaceful-kirch-69e06)
196 |
197 | It's also possible to override some view in the calendar completelly. Let's say that we want to add a today button in our calendars, when we click it we go to the today view:
198 | ```js
199 | class MyDTPicker extends React.Component {
200 | render() {
201 | return (
202 |
205 | this.renderView(mode, renderDefault)
206 | }
207 | />
208 | );
209 | }
210 |
211 | renderView(mode, renderDefault) {
212 | // Only for years, months and days view
213 | if (mode === "time") return renderDefault();
214 |
215 | return (
216 |
217 | {renderDefault()}
218 |
219 |
220 |
221 |
222 | );
223 | }
224 |
225 | goToToday() {
226 | // Reset
227 | this.refs.datetime.setViewDate(new Date());
228 | this.refs.datetime.navigate("days");
229 | }
230 | }
231 | ```
232 | [See it working](https://codesandbox.io/s/frosty-fog-nrwk2)
233 |
234 | #### Method Parameters
235 | * `props` is the object that the datepicker has calculated for this object. It is convenient to use this object as the `props` for your custom component, since it knows how to handle the click event and its `className` attribute is used by the default styles.
236 | * `selectedDate` and `currentDate` are [moment objects](http://momentjs.com) and can be used to change the output depending on the selected date, or the date for the current day.
237 | * `month` and `year` are the numeric representation of the current month and year to be displayed. Notice that the possible `month` values range from `0` to `11`.
238 |
239 | ## Make it work as a year picker or a time picker
240 | You can filter out what you want the user to be able to pick by using `dateFormat` and `timeFormat`, e.g. to create a timepicker, yearpicker etc.
241 |
242 | In this example the component is being used as a *timepicker* and can *only be used for selecting a time*.
243 | ```js
244 |
245 | ```
246 | [Working example of a timepicker here.](https://codesandbox.io/s/loving-nobel-sbok2)
247 |
248 | In this example you can *only select a year and month*.
249 | ```js
250 |
251 | ```
252 | [Working example of only selecting year and month here.](https://codesandbox.io/s/recursing-pascal-xl643)
253 |
254 | ## Blocking some dates to be selected
255 | It is possible to disable dates in the calendar if the user are not allowed to select them, e.g. dates in the past. This is done using the prop `isValidDate`, which admits a function in the form `function(currentDate, selectedDate)` where both arguments are [moment objects](http://momentjs.com). The function shall return `true` for selectable dates, and `false` for disabled ones.
256 |
257 | In the example below are *all dates before today* disabled.
258 |
259 | ```js
260 | import moment from 'moment';
261 | var yesterday = moment().subtract( 1, 'day' );
262 | var valid = function( current ){
263 | return current.isAfter( yesterday );
264 | };
265 |
266 | ```
267 | [Working example of disabled days here.](https://codesandbox.io/s/thirsty-shape-l4qg4)
268 |
269 | It's also possible to disable *the weekends*, as shown in the example below.
270 | ```js
271 | var valid = function( current ){
272 | return current.day() !== 0 && current.day() !== 6;
273 | };
274 |
275 | ```
276 | [Working example of disabled weekends here.](https://codesandbox.io/s/laughing-keller-3wq1g)
277 |
278 | ## Usage with TypeScript
279 |
280 | This project includes typings for TypeScript versions 1.8 and 2.0. Additional typings are not
281 | required.
282 |
283 | Typings for 1.8 are found in `react-datetime.d.ts` and typings for 2.0 are found in `typings/index.d.ts`.
284 |
285 | ```js
286 | import * as Datetime from 'react-datetime';
287 |
288 | class MyDTPicker extends React.Component {
289 | render() JSX.Element {
290 | return ;
291 | }
292 | }
293 | ```
294 |
295 | ## Contributions
296 | react-datetime is made by the community for the community. People like you, interested in contribute, are the key of the project! 🙌🙌🙌
297 |
298 | Have a look at [our contribute page](contribute-home.md) to know how to get started.
299 |
300 | ### [Changelog](CHANGELOG.md)
301 |
302 | ### [MIT Licensed](LICENSE.md)
303 |
--------------------------------------------------------------------------------
/config/env.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | const fs = require('fs');
4 | const path = require('path');
5 | const paths = require('./paths');
6 |
7 | // Make sure that including paths.js after env.js will read .env variables.
8 | delete require.cache[require.resolve('./paths')];
9 |
10 | const NODE_ENV = process.env.NODE_ENV;
11 | if (!NODE_ENV) {
12 | throw new Error(
13 | 'The NODE_ENV environment variable is required but was not specified.'
14 | );
15 | }
16 |
17 | // https://github.com/bkeepers/dotenv#what-other-env-files-can-i-use
18 | const dotenvFiles = [
19 | `${paths.dotenv}.${NODE_ENV}.local`,
20 | `${paths.dotenv}.${NODE_ENV}`,
21 | // Don't include `.env.local` for `test` environment
22 | // since normally you expect tests to produce the same
23 | // results for everyone
24 | NODE_ENV !== 'test' && `${paths.dotenv}.local`,
25 | paths.dotenv,
26 | ].filter(Boolean);
27 |
28 | // Load environment variables from .env* files. Suppress warnings using silent
29 | // if this file is missing. dotenv will never modify any environment variables
30 | // that have already been set. Variable expansion is supported in .env files.
31 | // https://github.com/motdotla/dotenv
32 | // https://github.com/motdotla/dotenv-expand
33 | dotenvFiles.forEach(dotenvFile => {
34 | if (fs.existsSync(dotenvFile)) {
35 | require('dotenv-expand')(
36 | require('dotenv').config({
37 | path: dotenvFile,
38 | })
39 | );
40 | }
41 | });
42 |
43 | // We support resolving modules according to `NODE_PATH`.
44 | // This lets you use absolute paths in imports inside large monorepos:
45 | // https://github.com/facebook/create-react-app/issues/253.
46 | // It works similar to `NODE_PATH` in Node itself:
47 | // https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders
48 | // Note that unlike in Node, only *relative* paths from `NODE_PATH` are honored.
49 | // Otherwise, we risk importing Node.js core modules into an app instead of Webpack shims.
50 | // https://github.com/facebook/create-react-app/issues/1023#issuecomment-265344421
51 | // We also resolve them to make sure all tools using them work consistently.
52 | const appDirectory = fs.realpathSync(process.cwd());
53 | process.env.NODE_PATH = (process.env.NODE_PATH || '')
54 | .split(path.delimiter)
55 | .filter(folder => folder && !path.isAbsolute(folder))
56 | .map(folder => path.resolve(appDirectory, folder))
57 | .join(path.delimiter);
58 |
59 | // Grab NODE_ENV and REACT_APP_* environment variables and prepare them to be
60 | // injected into the application via DefinePlugin in Webpack configuration.
61 | const REACT_APP = /^REACT_APP_/i;
62 |
63 | function getClientEnvironment(publicUrl) {
64 | const raw = Object.keys(process.env)
65 | .filter(key => REACT_APP.test(key))
66 | .reduce(
67 | (env, key) => {
68 | env[key] = process.env[key];
69 | return env;
70 | },
71 | {
72 | // Useful for determining whether we’re running in production mode.
73 | // Most importantly, it switches React into the correct mode.
74 | NODE_ENV: process.env.NODE_ENV || 'development',
75 | // Useful for resolving the correct path to static assets in `public`.
76 | // For example, .
77 | // This should only be used as an escape hatch. Normally you would put
78 | // images into the `src` and `import` them in code to get their paths.
79 | PUBLIC_URL: publicUrl,
80 | }
81 | );
82 | // Stringify all values so we can feed into Webpack DefinePlugin
83 | const stringified = {
84 | 'process.env': Object.keys(raw).reduce((env, key) => {
85 | env[key] = JSON.stringify(raw[key]);
86 | return env;
87 | }, {}),
88 | };
89 |
90 | return { raw, stringified };
91 | }
92 |
93 | module.exports = getClientEnvironment;
94 |
--------------------------------------------------------------------------------
/config/jest/cssTransform.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | // This is a custom Jest transformer turning style imports into empty objects.
4 | // http://facebook.github.io/jest/docs/en/webpack.html
5 |
6 | module.exports = {
7 | process() {
8 | return 'module.exports = {};';
9 | },
10 | getCacheKey() {
11 | // The output is always the same.
12 | return 'cssTransform';
13 | },
14 | };
15 |
--------------------------------------------------------------------------------
/config/jest/fileTransform.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | const path = require('path');
4 | const camelcase = require('camelcase');
5 |
6 | // This is a custom Jest transformer turning file imports into filenames.
7 | // http://facebook.github.io/jest/docs/en/webpack.html
8 |
9 | module.exports = {
10 | process(src, filename) {
11 | const assetFilename = JSON.stringify(path.basename(filename));
12 |
13 | if (filename.match(/\.svg$/)) {
14 | // Based on how SVGR generates a component name:
15 | // https://github.com/smooth-code/svgr/blob/01b194cf967347d43d4cbe6b434404731b87cf27/packages/core/src/state.js#L6
16 | const pascalCaseFilename = camelcase(path.parse(filename).name, {
17 | pascalCase: true,
18 | });
19 | const componentName = `Svg${pascalCaseFilename}`;
20 | return `const React = require('react');
21 | module.exports = {
22 | __esModule: true,
23 | default: ${assetFilename},
24 | ReactComponent: React.forwardRef(function ${componentName}(props, ref) {
25 | return {
26 | $$typeof: Symbol.for('react.element'),
27 | type: 'svg',
28 | ref: ref,
29 | key: null,
30 | props: Object.assign({}, props, {
31 | children: ${assetFilename}
32 | })
33 | };
34 | }),
35 | };`;
36 | }
37 |
38 | return `module.exports = ${assetFilename};`;
39 | },
40 | };
41 |
--------------------------------------------------------------------------------
/config/modules.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | const fs = require('fs');
4 | const path = require('path');
5 | const paths = require('./paths');
6 | const chalk = require('react-dev-utils/chalk');
7 | const resolve = require('resolve');
8 |
9 | /**
10 | * Get additional module paths based on the baseUrl of a compilerOptions object.
11 | *
12 | * @param {Object} options
13 | */
14 | function getAdditionalModulePaths(options = {}) {
15 | const baseUrl = options.baseUrl;
16 |
17 | // We need to explicitly check for null and undefined (and not a falsy value) because
18 | // TypeScript treats an empty string as `.`.
19 | if (baseUrl == null) {
20 | // If there's no baseUrl set we respect NODE_PATH
21 | // Note that NODE_PATH is deprecated and will be removed
22 | // in the next major release of create-react-app.
23 |
24 | const nodePath = process.env.NODE_PATH || '';
25 | return nodePath.split(path.delimiter).filter(Boolean);
26 | }
27 |
28 | const baseUrlResolved = path.resolve(paths.appPath, baseUrl);
29 |
30 | // We don't need to do anything if `baseUrl` is set to `node_modules`. This is
31 | // the default behavior.
32 | if (path.relative(paths.appNodeModules, baseUrlResolved) === '') {
33 | return null;
34 | }
35 |
36 | // Allow the user set the `baseUrl` to `appSrc`.
37 | if (path.relative(paths.appSrc, baseUrlResolved) === '') {
38 | return [paths.appSrc];
39 | }
40 |
41 | // If the path is equal to the root directory we ignore it here.
42 | // We don't want to allow importing from the root directly as source files are
43 | // not transpiled outside of `src`. We do allow importing them with the
44 | // absolute path (e.g. `src/Components/Button.js`) but we set that up with
45 | // an alias.
46 | if (path.relative(paths.appPath, baseUrlResolved) === '') {
47 | return null;
48 | }
49 |
50 | // Otherwise, throw an error.
51 | throw new Error(
52 | chalk.red.bold(
53 | "Your project's `baseUrl` can only be set to `src` or `node_modules`." +
54 | ' Create React App does not support other values at this time.'
55 | )
56 | );
57 | }
58 |
59 | /**
60 | * Get webpack aliases based on the baseUrl of a compilerOptions object.
61 | *
62 | * @param {*} options
63 | */
64 | function getWebpackAliases(options = {}) {
65 | const baseUrl = options.baseUrl;
66 |
67 | if (!baseUrl) {
68 | return {};
69 | }
70 |
71 | const baseUrlResolved = path.resolve(paths.appPath, baseUrl);
72 |
73 | if (path.relative(paths.appPath, baseUrlResolved) === '') {
74 | return {
75 | src: paths.appSrc,
76 | };
77 | }
78 | }
79 |
80 | /**
81 | * Get jest aliases based on the baseUrl of a compilerOptions object.
82 | *
83 | * @param {*} options
84 | */
85 | function getJestAliases(options = {}) {
86 | const baseUrl = options.baseUrl;
87 |
88 | if (!baseUrl) {
89 | return {};
90 | }
91 |
92 | const baseUrlResolved = path.resolve(paths.appPath, baseUrl);
93 |
94 | if (path.relative(paths.appPath, baseUrlResolved) === '') {
95 | return {
96 | '^src/(.*)$': '/src/$1',
97 | };
98 | }
99 | }
100 |
101 | function getModules() {
102 | // Check if TypeScript is setup
103 | const hasTsConfig = fs.existsSync(paths.appTsConfig);
104 | const hasJsConfig = fs.existsSync(paths.appJsConfig);
105 |
106 | if (hasTsConfig && hasJsConfig) {
107 | throw new Error(
108 | 'You have both a tsconfig.json and a jsconfig.json. If you are using TypeScript please remove your jsconfig.json file.'
109 | );
110 | }
111 |
112 | let config;
113 |
114 | // If there's a tsconfig.json we assume it's a
115 | // TypeScript project and set up the config
116 | // based on tsconfig.json
117 | if (hasTsConfig) {
118 | const ts = require(resolve.sync('typescript', {
119 | basedir: paths.appNodeModules,
120 | }));
121 | config = ts.readConfigFile(paths.appTsConfig, ts.sys.readFile).config;
122 | // Otherwise we'll check if there is jsconfig.json
123 | // for non TS projects.
124 | } else if (hasJsConfig) {
125 | config = require(paths.appJsConfig);
126 | }
127 |
128 | config = config || {};
129 | const options = config.compilerOptions || {};
130 |
131 | const additionalModulePaths = getAdditionalModulePaths(options);
132 |
133 | return {
134 | additionalModulePaths: additionalModulePaths,
135 | webpackAliases: getWebpackAliases(options),
136 | jestAliases: getJestAliases(options),
137 | hasTsConfig,
138 | };
139 | }
140 |
141 | module.exports = getModules();
142 |
--------------------------------------------------------------------------------
/config/paths.js:
--------------------------------------------------------------------------------
1 | const path = require('path');
2 | const fs = require('fs');
3 | const url = require('url');
4 |
5 | // Make sure any symlinks in the project folder are resolved:
6 | // https://github.com/facebook/create-react-app/issues/637
7 | const appDirectory = path.join( __dirname, '..' );
8 | const resolveApp = relativePath => path.resolve(appDirectory, relativePath);
9 |
10 | const envPublicUrl = process.env.PUBLIC_URL;
11 |
12 | function ensureSlash(inputPath, needsSlash) {
13 | const hasSlash = inputPath.endsWith('/');
14 | if (hasSlash && !needsSlash) {
15 | return inputPath.substr(0, inputPath.length - 1);
16 | } else if (!hasSlash && needsSlash) {
17 | return `${inputPath}/`;
18 | } else {
19 | return inputPath;
20 | }
21 | }
22 |
23 | const getPublicUrl = appPackageJson =>
24 | envPublicUrl || require(appPackageJson).homepage;
25 |
26 | // We use `PUBLIC_URL` environment variable or "homepage" field to infer
27 | // "public path" at which the app is served.
28 | // Webpack needs to know it to put the right