Skip to content

Commit

Permalink
Migrate www to typescript (#1537)
Browse files Browse the repository at this point in the history
* Rename all js, jsx to ts, tsx

* Add typescript configuration

* Add naive flow -> typescript convertor

* Add configuration to fix typescript code

* Convert flow to typescript

* Add more typings

* Fix double React bug

* Fix some simple typings

* Fix ExternalLink typing

* Fix ScrollToTop and React util

* Fix CORS notification

* Fix TimeslotTable

* Fix SearchBox

* Fix config

* Fix venues

* Fix CORS

* Fix StaticPage

* Fix query-string type version

* Fix ModulePageContainer test

* Fix some more stuff

* Fix custom module form

* Fix AddModule

* Fix TodayContainer

* Fix RefreshPrompt

* Fix VenueContainer

* Fixing things

* Revert e2e test code to JS

* Update packages

* Fix stuff

* Delete all Flow typedefs

* Fix even more stuff

* Update some configs

* Fix up eslint

* Fixing stuff

* Fixing more code

* Update stuff

* Maybe fix CI

* Fix stuff

* Fix more stuff

* Add simple fixes

* Add more simple fixes

* Fix footer

* Fix image types and global window extension

* Fix all reducers except undoHistory

* Fix global search test

* Add NUSModerator libdef

* Fix ExamCalendar

* Fix up Redux actions

* Fix bootstrapping (except config store

* Fix up test-utils

* Fix timetable export typing

* Fix today views

* Update planner types

* Fix layout components

* Fix simple components

* Update global and installed typings

Downgrade Jest typings to avoid bug with mockResolve/Reject

* Update module-info and ButtonGroup component

* Fix weekText test

* Fix typing for module pages

Still need to add a libdef for react-scrollspy

* Fix component types

TODO: Figure out how to type dynamic imports

* Fix selectors

* Fix planner reducer

* Fix Contribute container

* Improve venue typing

TODO: Fix react-leaflet types, timetable types

* Fix error components

* Fix middleware typing

* Fix settings views

* Fix routes typing

* Fix venueLocation JSON typing

* Fix CorsNotification test

* Fix storage strict errors

* Improve util types

* Add React Kawaii libdef

* Fix react-feather import

* Improve timetable typing

* Skip checking .d.ts files

* Fix more types

* Fix filter views

* Mark Disqus page as any

* Add json2mq types and fix CSs util

* Fix share timetable

* Fix BusStops and split ArrivalTimes

* Add react-scrollspy libdef

* Fix colors util

* Fix module page views

* Add react leaflet types

* Fix ImproveVenueForm

* Incomplete fixes for planner and filters

* Fix modulePage route

* Hack board.ts

* Fix request middleware test typing

* Fix Sentry typing

* Add more leaflet typings

* Fix TetrisGame

* Fix reducers test

* Add no-scroll libdef

* Fix BusStops test

* Fix api types

* Add typing for weather API responses

* Fix moduleBank and requests tests

* Fix minor bugs in planner and modtris typing

* Fix history debouncer test mock typing

* Fix storage types

* Ignore some minor TS errors

* Realign Timetable types

* Improve HOC typing

* Fix iCal tests

* Improve timetable test types

* Fix up more types

* Run eslint autofix

* Fix undoHistory type

* Fix lint errors

* Fix SVG component typing

* Fix filter groups

* Fix test configs

* Update snapshots

* Fix hoc typing

See: microsoft/TypeScript#28938 (comment)

* Fix jest tests

* Remove flow typings

* Fix timetable-export webpack config

* Clean up tsconfig

* Improve babel config

* Fix lint errors and improve typing

* Remove and simplify lint ignores

* Clean up more types

* Directly import react-feather icons

* Remove migration script

* Remove final traces of flow

* Clean up Babel configs

* Minor fixes and comments

* Remove unused packages

* Update README and add tsc to CI
  • Loading branch information
li-kai authored and ZhangYiJiang committed Feb 12, 2019
1 parent 3c8b36e commit 02d9abf
Show file tree
Hide file tree
Showing 433 changed files with 5,450 additions and 28,961 deletions.
6 changes: 3 additions & 3 deletions .circleci/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -108,12 +108,12 @@ jobs:
NODE_ENV: test
command: yarn
- save_cache: *save_node_deps
- run:
name: Type check code
command: yarn flow
- run:
name: Lint code
command: yarn lint:code --format junit -o reports/junit/js-lint-results.xml
- run:
name: Typecheck Code
command: yarn typecheck
- run:
name: Test code
environment:
Expand Down
59 changes: 42 additions & 17 deletions www/.eslintrc.js
Original file line number Diff line number Diff line change
@@ -1,34 +1,30 @@
const warnInDevelopment = process.env.NODE_ENV === 'production' ? 'error' : 'warn';

module.exports = {
parser: 'babel-eslint',
parser: '@typescript-eslint/parser',

parserOptions: {
project: './tsconfig.json',
},

root: true,
extends: [
'airbnb',
'plugin:flowtype/recommended',
'prettier',
'prettier/flowtype',
'prettier/react',
],
extends: ['airbnb', 'prettier', 'prettier/react'],
env: {
browser: true,
},
plugins: ['flowtype', 'prettier', 'import', 'jsx-a11y', 'react'],
plugins: ['@typescript-eslint', 'prettier', 'import', 'jsx-a11y', 'react'],

settings: {
'import/resolver': {
webpack: {
config: 'webpack/webpack.config.common.js',
},
},
},
overrides: [
{
files: ['**/*.test.{js,jsx}', '**/__mocks__/**/*.{js,jsx}'],
env: {
jest: true,
},
'import/parsers': {
'@typescript-eslint/parser': ['.ts', '.tsx'],
},
],
},

rules: {
'prettier/prettier': warnInDevelopment,

Expand All @@ -39,27 +35,40 @@ module.exports = {
'no-alert': 'off',
'prefer-destructuring': 'off',

// TODO: Should fix this - we don't want to accidentally create unresolvable dep chains
'import/no-cycle': 'off',

'import/extensions': [
warnInDevelopment,
'always',
{
js: 'never',
jsx: 'never',
ts: 'never',
tsx: 'never',
},
],

// Allow properties that are logically grouped together to be written
// without line breaks
'lines-between-class-members': 'off',

// Enable i++ in for loops
'no-plusplus': ['error', { allowForLoopAfterthoughts: true }],
'no-bitwise': 'off',

'react/no-array-index-key': 'off',

// SEE: https://github.com/yannickcr/eslint-plugin-react/issues
'react/no-unused-prop-types': 'off',

// Enables typing to be placed above lifecycle
'react/sort-comp': [
warnInDevelopment,
{
order: [
'type-annotations',
'instance-variables',
'static-methods',
'lifecycle',
'/^on.+$/',
Expand All @@ -68,10 +77,20 @@ module.exports = {
],
},
],

'react/require-default-props': 'off',
'react/jsx-filename-extension': ['error', { extensions: ['.tsx', '.jsx'] }],
'react/default-props-match-prop-types': ['error', { allowRequiredDefaults: true }],

// Too verbose, creates too many variables
'react/destructuring-assignment': 'off',

// TODO: Fix this
'react/no-access-state-in-setstate': 'warn',

// TODO: Replace divs with buttons, but remove all button styling.
'jsx-a11y/no-static-element-interactions': 'off',

// The default option requires BOTH id and nesting, which is excessive,
// especially with checkboxes and radiobuttons. This changes it to EITHER
'jsx-a11y/label-has-for': [
Expand All @@ -82,6 +101,7 @@ module.exports = {
},
},
],

// Link fails this rule as it has no "href" prop.
'jsx-a11y/anchor-is-valid': [
'error',
Expand All @@ -90,11 +110,16 @@ module.exports = {
specialLink: ['to'],
},
],

// Rule appear to be buggy when used with @typescript-eslint/parser
'jsx-a11y/label-has-associated-control': 'off',

// For use with immer
'no-param-reassign': [
'error',
{ props: true, ignorePropertyModificationsFor: ['draft', 'draftState'] },
],

// Let git handle the linebreaks instead.
'linebreak-style': 'off',
},
Expand Down
24 changes: 0 additions & 24 deletions www/.flowconfig

This file was deleted.

48 changes: 24 additions & 24 deletions www/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,10 @@ To run the development build, simply run:
$ yarn start
```

This will start webpack dev server, which will automatically rebuild and reload any code and components that you have changed. If your editor or IDE has built in support for Flow/ESLint/StyleLint, you can disable them to speed up the build process.
This will start Webpack dev server, which will automatically rebuild and reload any code and components that you have changed. If your editor or IDE has built in support for ESLint/StyleLint, you can disable them to speed up the build process.

```sh
$ DISABLE_ESLINT=1 DISABLE_FLOW=1 DISABLE_STYLELINT=1 yarn start
$ DISABLE_ESLINT=1 DISABLE_STYLELINT=1 yarn start
```

We recommend the following development tools to help speed up your work
Expand Down Expand Up @@ -168,11 +168,15 @@ type Props = {
}

type State = {
data: ?MyData,
data: MyData | null,
error?: any,
}

class MyComponent extends Component<Props> {
class MyComponent extends React.Component<Props, State> {
state: State = {
data: null,
};

componentDidMount() {
this.props.fetchData()
.then(data => this.setState({ data }))
Expand All @@ -186,7 +190,7 @@ class MyComponent extends Component<Props> {
return <ErrorPage />;
}

if (!data) {
if (data == null) {
return <LoadingSpinner />;
}

Expand All @@ -207,7 +211,7 @@ This is the [cache-then-network strategy described in the Offline Cookbook][offl
**Reducer example**
```js
```ts
import { SUCCESS } from 'types/reducers';
import { FETCH_DATA } from 'actions/example';

Expand All @@ -225,17 +229,17 @@ export function exampleBank(state: ExampleBank, action: FSA): ExampleBank {
**Component example**
```js
```ts
type Props = {
myData: ?MyData,
myData: MyData | null,
fetchData: () => Promise<MyData>,
}

type State = {
error?: any,
}

class MyComponent extends Component<Props> {
class MyComponent extends React.Component<Props, State> {
componentDidMount() {
this.props.fetchData()
.catch(error => this.setState({ error });
Expand All @@ -250,7 +254,7 @@ class MyComponent extends Component<Props> {
return <ErrorPage />;
}

if (!data) {
if (data == null) {
return <LoadingSpinner />;
}

Expand All @@ -271,21 +275,16 @@ If you need to access the status of a request from outside the component which i
NUSMods tries to be as lean as possible. Adding external dependencies should be done with care to avoid bloating our bundle. Use [Bundlephobia][bundlephobia] to ensure the new dependency is reasonably sized, or if the dependency is limited to one specific page/component, use code splitting to ensure the main bundle's size is not affected.
#### Flow libdef
#### TypeScript libdef
When adding a JavaScript package, Flow requires a library definition, or libdef. To try to install one from the [community repository][flow-typed], use the `flow-typed` command. If a community libdef is not available, the same command can also be used to create a stub libdef which you can use immediately in a pinch, or edit to fill in the correct definitions.
When adding a JavaScript package, Flow requires a library definition, or libdef. To try to install one from the [community repository][definitely-typed], install `@types/<package name>`. Make sure the installed libdef's version matches that of the package.
```sh
# Use ./node_modules/.bin/flow-typed if you don't want to use npx
npx flow-typed install [email protected]
If a community libdef is not available, you can try writing your own and placing it in `js/types/vendor`.
# Use create-stub for packages without community libdef
npx flow-typed create-stub my-dep
```
### Testing and Linting
We use [Jest][jest] with [Enzyme][enzyme] to test our code and React components, [Flow][flow] for typechecking, [Stylelint][stylelint] and [ESLint][eslint] using [Airbnb config][eslint-airbnb] and [Prettier][prettier] for linting and formatting.
We use [Jest][jest] with [Enzyme][enzyme] to test our code and React components, [TypeScript][ts] for typechecking, [Stylelint][stylelint] and [ESLint][eslint] using [Airbnb config][eslint-airbnb] and [Prettier][prettier] for linting and formatting.
```sh
# Run all tests once with code coverage
Expand All @@ -305,8 +304,8 @@ $ yarn lint:code
# p.s. Use yarn lint:styles --fix with care (it's experimental),
# remember to reset changes for themes.scss.
# Run Flow type checking
$ yarn flow
# Run TypeScript type checking
$ yarn typecheck
```
#### End to End testing
Expand Down Expand Up @@ -366,7 +365,8 @@ $ yarn promote-staging # Promote ./dist to production
│   │   ├── test-utils - Utilities for testing - this directory is not counted
│   │   │ for test coverage
│   │   ├── timetable-export - Entry point for timetable only build for exports
│   │   ├── types - Flow type definitions
│   │   ├── types - Type definitions
│   │   └── vendor - Types for third party libaries
│   │   ├── utils - Utility functions and classes
│   │   └── views
│   │   ├── components - Reusable components
Expand Down Expand Up @@ -411,7 +411,7 @@ Components should keep their styles and tests in the same directory with the sam
[bootstrap]: https://getbootstrap.com/
[jest]: https://facebook.github.io/jest/
[enzyme]: http://airbnb.io/enzyme/
[flow]: https://flow.org/
[ts]: https://www.typescriptlang.org/
[eslint]: https://eslint.org/
[svgr]: https://github.com/smooth-code/svgr
[eslint-airbnb]: https://www.npmjs.com/package/eslint-config-airbnb
Expand All @@ -421,5 +421,5 @@ Components should keep their styles and tests in the same directory with the sam
[css-modules]: https://github.com/css-modules/css-modules
[offline-cookbook]: https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#cache-then-network
[axios-config]: https://github.com/axios/axios#request-config
[flow-typed]: https://github.com/flow-typed/flow-typed
[definitely-typed]: https://github.com/DefinitelyTyped/DefinitelyTyped/
[bundlephobia]: https://bundlephobia.com/
5 changes: 4 additions & 1 deletion www/babel.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ module.exports = (api) => {
const IS_TEST = api.env('test');

const presets = [
'@babel/preset-typescript',
[
'@babel/preset-env',
{
Expand All @@ -18,7 +19,6 @@ module.exports = (api) => {
},
],
['@babel/preset-react', { development: !IS_PROD }],
'@babel/preset-flow',
];

const plugins = [
Expand All @@ -33,9 +33,11 @@ module.exports = (api) => {
if (IS_DEV || IS_PROD) {
plugins.push(['@babel/plugin-proposal-object-rest-spread', { useBuiltIns: true }]);
}

if (IS_DEV) {
plugins.push('react-hot-loader/babel');
}

if (IS_PROD) {
// React Optimize plugins
plugins.push(
Expand All @@ -45,6 +47,7 @@ module.exports = (api) => {
'babel-plugin-transform-react-class-to-function',
);
}

if (IS_TEST) {
plugins.push('babel-plugin-dynamic-import-node');
}
Expand Down
18 changes: 0 additions & 18 deletions www/flow-typed/npm/@sentry/browser_vx.x.x.js

This file was deleted.

Loading

0 comments on commit 02d9abf

Please sign in to comment.