首页 > 其他分享 >webpack - 构建支持TypeScript的React应用

webpack - 构建支持TypeScript的React应用

时间:2023-10-06 14:33:07浏览次数:45  
标签:react TypeScript index babel React webpack env true

1. 初始化package.json

  • 创建项目文件夹
    mkdir webpack-react-ts
    cd webpack-react-ts
  • 初始化项目package.json
    yarn init -y
{
  "name": "webpack-react-ts",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
}

2. 添加必要的依赖包

  • 项目依赖
    react, react-dom

  • 开发依赖
    编译器:babel (core, env, react, ts and loader)
    跨平台环境变量配置:cross-env
    webpack插件:html-webpack-plugin
    serve: 提供访问静态网站,或单页应用的服务
    webpack插件(js压缩优化):terser-webpack-plugin
    Typescript语言支持:typescript
    Types相关的类型定义包:@types/
    webpack相关:webpack (core, cli, dev-server)

"dependencies": {
  "react": "^16.12.0",
  "react-dom": "^16.12.0"
},
"devDependencies": {
  "@babel/core": "^7.7.7",
  "@babel/preset-env": "^7.7.7",
  "@babel/preset-react": "^7.7.4",
  "@babel/preset-typescript": "^7.7.7",
  "@types/node": "^12.12.5",
  "@types/react": "^16.9.11",
  "@types/react-dom": "^16.9.3",
  "babel-loader": "^8.0.6",
  "cross-env": "^6.0.3",
  "html-webpack-plugin": "^3.2.0",
  "serve": "^11.3.0",
  "terser-webpack-plugin": "^2.3.2",
  "typescript": "^3.7.4",
  "webpack": "^4.41.5",
  "webpack-cli": "^3.3.10",
  "webpack-dev-server": "^3.10.1"
}

3. 添加必要的脚本命令

  • 使用cross-env 设置环境变量
  • 使用webpack-dev-server 启动开发服务器
  • 使用webpack进行打包编译
  • 使用serve 提供访问网站服务
"scripts": {
  "dev": "cross-env NODE_ENV=development webpack-dev-server",
  "build": "cross-env NODE_ENV=production webpack",
  "start": "serve dist"
},
  • 使用yarn命令安装应用依赖包

4. 添加babel配置文件 .babelrc

{
  "presets": ["@babel/env", "@babel/react", "@babel/typescript"]
}

5. 添加tsconfig.json 支持typescript语言开发

tsc --init

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "jsx": "react",
    "moduleResolution": "node",
    "strict": true,
    "noEmit": true,
    "allowJs": true,
    "skipLibCheck": true,
    "isolatedModules": true,
    "esModuleInterop": true
  },
  "include": ["src"]
}

6. 配置webpack

  • entry 指出应用程序的入口文件
  • output 指出webpack打包后的应用程序文件目录
  • modules 配置文件转换规则

// webpack.config.js

const { resolve } = require("path");
const HtmlWebpackPlugin=require("html-webpack-plugin");
const TerserWebpackPlugin=require("terser-webpack-plugin");

const isProd=process.env.NODE_ENV === "production";

const config={
  mode: isProd ? "production" : "development",
  entry: {
    index: "./src/index.tsx",
  },
  output: {
    path: resolve(__dirname, "dist"),
    filename: "bundle.js",
  },
  resolve: {
    extensions: [".js", ".jsx", ".ts", ".tsx"],
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: "babel-loader",
        exclude: /node_modules/,
      },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: "./src/index.html",
      filename: "index.html",
      inject: "body",
    }),
  ],
};

if (isProd) {
  config.optimization={
    minimizer: [new TerserWebpackPlugin()],
  };
} else {
  config.devServer={
    port: 9000,
    open: true,
    hot: true,
    compress: true,
    stats: "errors-only",
    overlay: true,
  };
}

module.exports=config;

7. 添加React相关文件

  • index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Webpack with React TS</title>
  </head>
  <body></body>
</html>
  • index.tsx
import React from 'react'
import { render } from 'react-dom'
import App from './App'
 
render(<App />, document.body)
  • App.tsx
import React from "react";
const App: React.FC:(props) => {
  return <div>Webpack is cool!</div>;
};
 
export default App;

8. 启动应用

  • yarn dev : 启动开发服务器
  • yarn build : 打包应用
  • yarn start : 启动产品服务

[参考] https://www.skcript.com/svr/using-webpack-with-react-typescript

标签:react,TypeScript,index,babel,React,webpack,env,true
From: https://www.cnblogs.com/xiaodi-js/p/17744555.html

相关文章

  • react native 毛玻璃效果
    importReactfrom'react'import{View,Text,FlatList}from'react-native'import{Skeleton}from'@rneui/themed'importuseListfrom'./useList'import{Image}from'../../../../component/light'im......
  • typescript: Prototype Pattern
     /***PrototypePattern原型是一种创建型设计模式,使你能够复制对象,甚至是复杂对象,而又无需使代码依赖它们所属的类。*Theexampleclassthathascloningability.We'llseehowthevaluesoffield*withdifferenttypeswillbecloned.*/classPrototype......
  • 2023年React Native vs Flutter,究竟谁能更胜一筹?
    前言大约两年前,当时我对Flutter还有些陌生,对它给予了很高的评价,但也对ReactNative表示了一些敬意。我对ReactNative有更多的经验,并且喜欢(并且仍然喜欢)它的WebOG,ReactJS。差不多两年后,我会说我已经变得不那么公正了。长话短说,我觉得Flutter绝对是更好的移动框架。Flutter......
  • typescript: Builder Pattern
     /***TypeScript实体类Model*BuilderPattern*生成器是一种创建型设计模式,使你能够分步骤创建复杂对象。*https://stackoverflow.com/questions/12827266/get-and-set-in-typescript*https://github.com/Microsoft/TypeScript/wiki/Coding-guidelines*/cl......
  • 什么是 TypeScript 的类型增强功能
    TypeScript的类型增强(TypeAugmentation)是一种功能,它允许您扩展现有类型的成员,以添加新的属性或方法,以及修改已有属性或方法的类型定义。这个功能让您可以更好地适应第三方库或原始代码,以便在不修改源代码的情况下添加自定义的类型信息。在本文中,我将详细介绍TypeScript的类型增......
  • TypeScript入门到精通——TypeScript类型系统基础——单元类型、顶端类型、尾端类型
    单元类型 单元类型(UnitType)也叫作单例类型(SingletonType),指的是仅包含一个可能值的类型。由于这个特殊的性质,编译器在处理单元类型时甚至不需要关注单元类型表示的具体值。 TypeScript中的单元类型有以下几种:undefined类型null类型uniquesymbol类型void类型......
  • TypeScript入门到精通——TypeScript类型系统基础——字面量类型
    字面量类型 TypeScript支持将字面量作为类型使用,我们称之为字面量类型。每一个字面量类型都只有一个可能的值,即字面量本身。1、boolean字面量类型 boolean字面量类型只有以下两种:true字面量类型false字面量类型 原始类型boolean等同于由true字面量类型......
  • [Compose] Asynchronous Reactive Data with Promises
    Let’smakeusingtheobserversasynchronous!Thiswaywecanupdatethedataandhavemultipleobserversrunasynchronously.classAsyncData{constructor(initialData){this.data=initialData;this.subscribers=[];}//Subscribetochan......
  • 什么是 TypeScript 的类型增强功能
    TypeScript的类型增强(TypeAugmentation)是一种功能,它允许您扩展现有类型的成员,以添加新的属性或方法,以及修改已有属性或方法的类型定义。这个功能让您可以更好地适应第三方库或原始代码,以便在不修改源代码的情况下添加自定义的类型信息。在本文中,我将详细介绍TypeScript的类型......
  • 如何使用 TypeScript 的 module augmentation 技术增强 Spartacus Feature Library
    moduleaugmentation技术是一种强大的TypeScript功能,它允许开发人员在不修改原始代码的情况下扩展现有模块的功能。这种技术在Angular生态系统中的应用尤为广泛,特别是在构建功能库和插件时,以确保代码的可维护性和可扩展性。概述Moduleaugmentation允许我们向现有模块添加......