The process that React uses to generate JavaScript from JSX files creates an extra step in the normal development workflow. Our TypeScript .tsx files, once compiled, will generate JavaScript files that convert JSX syntax into a series of calls to the React libraries. As an example, using a <div> element in our .tsx file will create a call to React.createElement("div", ...) in the compiled JavaScript file. These compiled files then need to be combined with the React libraries themselves in order to produce runnable code. For this reason, it is recommended to use a bundling tool such as Webpack to combine the output of the compilation step with the React libraries themselves. Webpack will also create a single output file for loading into a browser, in a process called bundling.
To start a new React project, we will follow a few steps. Firstly, create a directory for your project, and initialize npm, as follows:
mkdir react-sample cd react-sample npm init
Here, we create the directory for our project, change into the directory, and initialize npm in the project directory. This will create a package.json file for us that npm can use. Once initialized, we can install webpack as follows:
npm install -g webpack npm install -g webpack-cli
This installs webpack as a global Node module, and the command-line interface for webpack, named webpack-cli. Note that, even though we have webpack installed globally, the webpack command-line tool will still need to find the webpack modules under the node_modules directory. This means that we also need to install webpack as a local module as follows:
npm install webpack --save-dev
npm install webpack-cli -save-dev
We can now install React, as follows:
npm install react react-dom
This installs the react and react-dom libraries into the node_modules directory. We will need a number of other utilities, as follows:
npm install --save-dev ts-loader source-map-loader
This installs the ts-loader and source-map-loader utilities as development dependencies. We will also need to install Boostrap as we did with our previous projects, as follows:
npm install bootstrap
Once Bootstrap has been installed, we can then install the react declaration files through the @types syntax as follows:
npm install @types/react --save-dev npm install @types/react-dom --save-dev