Webpack 4 + React + Typescript 搭建启动模版

2019年是个崭新的开始,在过去半年的工作中我参与到公司一个大型项目的维护和开发中,深深的体会到了react项目中数据流向复杂,参数类型错乱带来的痛苦体验,于是在崭新的一年我决定拥抱Typescript来解决避免在以后的项目中遇到同样痛苦的问题。

这里先从一个简单的Webpack 4 + React + Typescript 配置模版开始。

首先,我们需要建立文件的基本结构:

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

cd proj初始化项目

npm init

然后开始安装依赖:webpack

npm i webpack webpack-cli -D

创建webpack.config.js

const path = require('path');
module.exports = {
  entry: "./src/index.tsx",
  output: {
    path: path.join(__dirname, '/dist'),
    filename: 'bundle.js'
  }
};

安装typescript 加载器

npm i typescript awesome-typescript-loader source-map-loader -D

配置脚本 typescript tsconfig.json

{
  "compilerOptions": {
  "outDir": "./dist/",
  "sourceMap": true,
  "noImplicitAny": true,
  "module": "commonjs",
  "target": "es5",
  "jsx": "react"
  },
 "include": [
   "./src/**/*” 
  ]
}

在webpack.config.js 加入文件扩展名解析

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

引入react依赖

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

@ types /前缀意味着我们还想获取React和React-DOM的声明文件

在根目录添加html脚本 indec.html

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

在src目录添加入口文件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")
);

在src/components目录添加一个Hello.tsx组件,用了react的function 无状态组件 和typescript 的interface

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>
);

引入html-webpack-plugin 实现html模版自动生成

npm i html-webpack-plugin -D

完整的webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
 
module.exports = {
  entry: "./src/index.tsx",
  output: {
    path: path.join(__dirname, '/dist'),
    filename: 'bundle.js'
  },
  devtool: "source-map",
  resolve: {
  // Add '.ts' and '.tsx' as resolvable extensions.
   extensions: [".ts", ".tsx", ".js", ".json"]
  },
  module: {
    rules: [
      // All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader’.  
      { test: /\.tsx?$/, loader: "awesome-typescript-loader" },
      // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
      { enforce: "pre", test: /\.js$/, loader: "source-map-loader" }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
    template: './index.html'
   })
  ],
  // 用来替换全局变量
  // externals: {
    // react: "React",
    // "react-dom": "ReactDOM"
// }
};

引入webpack-dev-server

npm i webpack-dev-server --D

更新package.json

"scripts": {
  "start": "webpack-dev-server --mode development --open --hot",
  "build": "webpack --mode production"
}

运行npm start 在浏览器打开默认端口localhost:8080 查看