原文: Getting Started with React TypeScript and Webpack
做者:Grant
译者:博轩
我会经过这篇文章,为你们讲述,如何使用 React
,TypeScript
和 Webpack
来构建一个项目。javascript
这是一篇关于如何使用 React
,TypeScript
和 Webpack
来构建一个很是基础的项目的教程。您能够继续阅读,或者直接在 github 上面查看示例代码。html
译注:create-react-app
已经提供了关于TypeScript
开箱即用的支持,也可使用react-scripts
或者react-app-rewired
完成对于Webpack
配置的扩展。本文也只是聊一聊如何从 0 构建一个项目,你们了解一下就好 🤣
mkdir your-folder-name && cd your-folder-name && npm init --yes复制代码
React
和 React-DOM
的依赖npm install react && npm install react-dom复制代码
TypeScript
npm install typescript --save-dev复制代码
React
和 React-DOM
的类型npm install @types/react --save-dev && npm install @types/react-dom --save-dev复制代码
TypeScript
项目。您应该 tsconfig.json
文件被建立。tsc --init复制代码
tsconfig.json
,以后添加一个 include
compilerOptions
。这将告诉 TypeScript
在哪找到咱们的代码。{
"compilerOptions": {
},
"include":[
"./src/**/*"
]
}复制代码
src
文件夹,并在里面建立一个 App.ts
文件。export class App
{
constructor()
{
console.log("Hello app!");
}
}复制代码
TypeScript
是经过 tsc
命令在终端中运行编译。若是成功,您应该看到 src
文件夹下面出现 App.js
的文件。完成后,咱们删除 .js
文件,继续后续操做。如今,让咱们看看 TypeScript
是否能够编译 React
文件。java
tsconfig.json
文件,内容以下。{
"compilerOptions": {
"target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
"lib": ["es5", "es6", "dom"], /* Specify library files to be included in the compilation. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
"jsx": "react", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
"sourceMap": true, /* Generates corresponding '.map' file. */
"outDir": "./dist/", /* Redirect output structure to the directory. */
"removeComments": true, /* Do not emit comments to output. */
"noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
"allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
"preserveConstEnums": true
},
"include": [
"./src/**/*"
]
}复制代码
TypeScript
是否能够转换 React
文件,咱们将在 src 文件夹中添加一个新文件 Main.tsx
。import * as React from 'react';
import { App } from './App';
export interface IMainProps
{
app: App;
}
export class Main extends React.Component<IMainProps, {}>
{
public render(): JSX.Element
{
return (
<> <h1>Hello main</h1> </> ); } }复制代码
tsc
,您如今应该看到生成了一个 dist
文件夹,切该目录下有一个 Main.js
文件,这意味着 TypeScript
如今也能够处理 React TypeScript
文件!(.tsx)如今,咱们须要将 TypeScript
和 React
结合在一块儿开发。接下来,咱们会使用 Webpack
进行打包,并在浏览器中提供服务。node
首先,咱们按照Webpack 官方文档 在本地安装 Webpack 。react
npm install webpack --save-dev &&
npm install webpack-cli --save-dev &&
npm install webpack-dev-server --save-dev &&
npm install awesome-typescript-loader --save-dev &&
npm install html-webpack-plugin --save-dev复制代码
如今,除了 Webpack
,咱们还安装了另外4个开发依赖。webpack
tsconfig.json
帮助 Webpack
编译咱们的 TypeScript
代码。webpack.config.js
文件。const path = require('path');
const HtmlWebPackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
app: ['./src/App.ts'],
vendor: ['react', 'react-dom']
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'js/[name].bundle.js'
},
devtool: "source-map",
resolve: {
extensions: [".ts", ".tsx", ".js", ".jsx", ".json"]
},
module: {
rules: [
{
test: /\.tsx?$/,
loader: "awesome-typescript-loader"
}
]
},
plugins: [
new HtmlWebPackPlugin({
template: "./src/index.html"
})
]
};复制代码
entry
包含 App.ts
的文件路径。entry
还包含 verder
数组,React
和 React-Dom
是咱们惟一的库,因此咱们在这里添加它们。若是要添加其余库,则应将其添加到此,以便 Webpack 了解项目中所须要的依赖。output
对象告诉 webpack
在哪里打包咱们的应用程序,当前的例子是在 dist
文件夹里面。module
下咱们添加了 awesome-type-script-loader
。plugins
数组下,咱们使用 HtmlWebPackPlugin
添加了 index.html
源文件。压缩后的 html
文件将放在咱们的 dist
文件夹中,同时引用咱们打包后的js文件。接下来,新建立一个 index.html
文件并将其添加到咱们的src文件夹中。并确保<div id="app"></div>
已被添加在 index.html
文件中。这是咱们的React应用程序将要渲染的位置。git
App.ts
并在文件的最底部添加 new App()
;export class App
{
constructor()
{
console.log("Hello app!");
}
}
new App();复制代码
node_modules/.bin/webpack-dev-server --mode development复制代码
如今咱们已经完成了React
,TypeScript
和 Webpack
的组合,让咱们看一个更加实用一些的 React
示例。es6
Main.tsx
文件:import * as React from 'react';
import { App } from './App';
export interface IMainProps
{
app: App; // Reference to our App.ts class
}
export class Main extends React.Component<IMainProps, {}>
{
constructor(props: IMainProps)
{
super(props);
}
public render(): JSX.Element
{
return (
<> Main app </> ); } }复制代码
App.ts
文件,并粘贴以下内容:import * as ReactDOM from 'react-dom';
import * as React from 'react';
import { Main } from './Main';
export class App
{
constructor()
{
this.render();
}
private render(): void
{
ReactDOM.render(React.createElement(Main, { app: this }), document.getElementById("app"));
}
}
new App();复制代码
Main.tsx
类做为渲染的 React UI 的入口。props
传递。可能会在之后的App类中执行或访问这些内容。app
id 属性定位 index.html
文件。这也将是React呈现的位置。如今,若是咱们回到浏览器,咱们应该在页面上看到 github
使用 ./node_modules/.bin/webpack-dev-server --mode development
运行项目不是那么友好。咱们可使用更加便捷的 node
命令。web
修改 package.json
以下:
{
"scripts": {
"dev": "webpack-dev-server --mode development",
"build": "webpack --mode production"
}
}复制代码
咱们如今能够在终端上运行上面的命令:
npm run dev
就是咱们以前输入的内容:./node_modules/.bin/webpack-dev-server --mode development
npm run build
将告诉 webpack
编译咱们的应用程序用于生产。它将压缩并打包全部内容到咱们的 dist
文件夹中,准备上传到网络。本文已经联系原文做者,并受权翻译,转载请保留原文连接