yaoningvital/blog

使用react、webpack、typescript,手动搭建一个项目

Opened this issue · 0 comments

示例:http://www.typescriptlang.org/docs/handbook/react-&-webpack.html

Step1:创建项目文件夹结构

创建一个如下的项目结构:

proj/
├─ dist/
└─ src/
   └─ components/

1、新建一个名为 proj 的文件夹;在里面新建一个 src 文件夹,src 中新建一个 components 文件夹。
2、dist 文件夹不用手动创建,最后用webpack打包之后,会自动生成。

Step2:初始化项目

在项目根目录下执行下面的命令:

npm init -y

这个命令将在项目根目录下创建一个使用默认值的package.json文件。

Step3:安装依赖

1、首先安装webpack

npm i --save-dev webpack webpack-cli

webpack是一个工具,它可以将你写的代码和所有的依赖打包到一个单独的.js文件。

2、安装 react、react-dom,和它们的类型定义文件

npm i --save react react-dom
npm i --save-dev @types/react @types/react-dom

3、安装 typescript、ts-loader、source-map-loader

npm i --save-dev typescript ts-loader source-map-loader

1、ts-loader 帮助webpack 使用 ts 的标准配置文件 tsconfig.json 对typescript 文件进行编译。
2、ts-loader 不是唯一的编译 typescript 的loader。

Step4:添加 TypeScript 配置文件 tsconfig.json

在项目根目录下创建一个文件 tsconfig.json,内容如下:

{
    "compilerOptions": {
        "outDir": "./dist/",
        "sourceMap": true,
        "noImplicitAny": true,
        "module": "commonjs",
        "target": "es6",
        "jsx": "react"
    }
}

Step5:写代码

1、在 src/components 下创建一个 Hello.tsx 组件

Hello.tsx组件内容如下:

import * as React from 'react';
export interface HelloProps { compiler: string, framework: string };
export const Hello = (props: HelloProps )=> <h1>Hello from {props.compiler} and {props.framework}</h1>

上面这个Hello组件是一个函数组件,可以把它写成类组件:

import * as React from 'react';
export interface HelloProps { compiler: string, framework: string };
// HelloProps 描述了 组件接收的 props 的类型
// 组件本身的状态属性 this.state 并没有设置,所以用 '{}' 这个类型
export class Hello extends React.Component<HelloProps, {}>{ 
    render () {
        return <h1>Hello from { this.props.compiler } and { this.props.framework } ! </h1>
    }
}

2、在 src 目录下创建入口文件 index.tsx

index.tsx 代码如下:

import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { Hello } from './components/Hello';

ReactDOM.render(
    <Hello compiler="TypeScript" framework="React" />,
    document.getElementById('example')
)

3、在项目根目录下创建 index.html 文件

index.html 文件需要手动引用打包后的文件,webpack 默认打包后的文件名称为 main.js,放在 dist 目录下。
index.html 代码如下:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <title>Hello React!</title>
    </head>
    <body>
        <div id="example"></div>

        <!-- Dependencies -->
        <script src="./node_modules/react/umd/react.development.js"></script>
        <script src="./node_modules/react-dom/umd/react-dom.development.js"></script>

        <!-- Main -->
        <script src="./dist/main.js"></script>
    </body>
</html>

Step6、创建 webpack 的配置文件

在项目根目录下创建 webpack.config.js 配置文件,内容如下:

module.exports = {
    mode: "production",

    // Enable sourcemaps for debugging webpack's output.
    devtool: "source-map",

    resolve: {
        // Add '.ts' and '.tsx' as resolvable extensions.
        extensions: [".ts", ".tsx"]
    },

    module: {
        rules: [
            {
                test: /\.ts(x?)$/,
                exclude: /node_modules/,
                use: [
                    {
                        loader: "ts-loader"
                    }
                ]
            },
            // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
            {
                enforce: "pre",
                test: /\.js$/,
                loader: "source-map-loader"
            }
        ]
    },

    // When importing a module whose path matches one of the following, just
    // assume a corresponding global variable exists and use that instead.
    // This is important because it allows us to avoid bundling all of our
    // dependencies, which allows browsers to cache those libraries between builds.
    externals: {
        "react": "React",
        "react-dom": "ReactDOM"
    }
};

Step7:打包

在项目根目录下,执行下面的命令:

npx webpack

命令执行完成后,将在根目录下生成一个 dist 文件夹,里面有一个 main.js 文件,同时还有一个 main.js 的映射文件 main.js.map。如下图所示:
image

现在,在浏览器中打开 index.html 文件,将看到 "Hello from Typescript and React" 这个h1标签。