【譯】使用 React,TypeScript 和 Webpack 開始一個項目

原文:Getting Started with React TypeScript and Webpack
作者:Grant
譯者:博軒

我會通過這篇文章,爲大家講述,如何使用 ReactTypeScriptWebpack 來構建一個項目。

開始

這是一篇關於如何使用 ReactTypeScriptWebpack 來構建一個非常基礎的項目的教程。您可以繼續閱讀,或者直接在 github 上面查看示例代碼。

譯註:create-react-app 已經提供了關於 TypeScript 開箱即用的支持,也可以使用 react-scripts 或者 react-app-rewired 完成對於 Webpack 配置的擴展。本文也只是聊一聊如何從 0 構建一個項目,大家瞭解一下就好 🤣

設置項目

  • 爲你的項目創建一個文件夾
mkdir your-folder-name && cd your-folder-name && npm init --yes
  • 爲項目安裝 ReactReact-DOM 的依賴
npm install react && npm install react-dom
  • 根據我們的項目配置需求,我們需要 TypeScript
npm install typescript --save-dev
  • 安裝 ReactReact-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 文件,繼續後續操作。

TypeScriptReact 一起工作

現在,讓我們看看 TypeScript 是否可以編譯 React 文件。

  • 讓我們更新 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)

整合 Webpack

現在,我們需要將 TypeScriptReact 結合在一起開發。接下來,我們會使用 Webpack 進行打包,並在瀏覽器中提供服務。

首先,我們按照Webpack 官方文檔 在本地安裝 Webpack 。

  • 在終端運行以下命令
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-cli - 在終端提供有用的 Webpack 命令。
    • Webpack dev server - 爲我們的應用提供服務端的支持,如果我們修改代碼,可以幫我們刷新瀏覽器的頁面。
    • Awesome Typescript Loader - 使用 tsconfig.json 幫助 Webpack 編譯我們的 TypeScript 代碼。
    • HTML Webpack Plugin - 簡化HTML文件的創建,爲 Webpack 提供打包服務。
  • 讓我們在根目錄創建 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 數組,ReactReact-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應用程序將要渲染的位置。

  • 打開 App.ts 並在文件的最底部添加 new App() ;
export class App
{
    constructor()
    {
        console.log("Hello app!");
    }
}

new App();
  • 現在,使用終端,在項目的根目錄下,運行:
node_modules/.bin/webpack-dev-server  --mode development
  • 你現在應該會有一個成功的構建,並在 http://localhost:8080/ 可以看到 Web 服務已經啓動。
  • 檢查開發控制檯,您還應該在控制檯中看到我們的日誌:“Hello app!”

使用更多的 React

現在我們已經完成了ReactTypeScriptWebpack的組合,讓我們看一個更加實用一些的 React 示例。

  • 創建一個 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 的入口。
  • 我們將對App類的引用作爲 props 傳遞。可能會在以後的App類中執行或訪問這些內容。
  • 通過 app id 屬性定位 index.html 文件。這也將是React呈現的位置。

現在,如果我們回到瀏覽器,我們應該在頁面上看到 “Main app”。當我們更改了一些代碼,您的瀏覽器應該已經自動重新加載。現在 React 已經出現在我們的網頁中了。

整合發佈

使用 ./node_modules/.bin/webpack-dev-server --mode development 運行項目不是那麼友好。我們可以使用更加便捷的 node 命令。

修改 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 文件夾中,準備上傳到網絡。
本文已經聯繫原文作者,並授權翻譯,轉載請保留原文鏈接
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章