美文网首页React技术前端开发那些事儿
webpack + react + typescript 项目从

webpack + react + typescript 项目从

作者: 咕嘟咕嘟li | 来源:发表于2021-06-12 17:37 被阅读0次

    新建文件夹 redux-demo后,执行npm init

    1. 执行以下命令
    npm install --save-dev webpack webpack-cli webpack-dev-server
    
    • *注意: 目前为止这样安装好的webpack版本是5.38.1 webpack-cli版本是4.7.2

    项目运行时会报错,所以进行了降级,webpack使用4.38.1,webpack-cli版本是3.3.2

    2. 新建webpack.config.js文件内容如下
    const path = require('path')
    module.exports = {
      entry: {
        main: path.join(__dirname, 'src/index')
      },
      plugins: [
      ],
      module: {
        rules:[]
      },
      output: {
        path: path.join(__dirname, 'dist'),
        filename: 'bundle.js'
      }
    }
    
    
    3. 配置package.json的script
    "start": "webpack-dev-server --port 1100",
    "build": "webpack"
    
    4. 新建public/index.html文件, 新建src/index.js文件
    <!-- public/index.html -->
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Document</title>
    </head>
    <body>
      <div id="root"></div>
    </body>
    </html>
    
    // src/index.js
    import React from 'react'
    import ReactDOM from 'react-dom'
    
    class App extends React.Component {
      render() {
        return <div>hello world</div>
      }
    }
    
    ReactDOM.render(<App />, document.getElementById('root'))
    
    5. 执行以下命令
    npm install --save-dev html-webpack-plugin clean-webpack-plugin
    

    webpack.config.js配置如下插件

    // 引入插件
    const HtmlWebpackPlugin = require('html-webpack-plugin')
    const {CleanWebpackPlugin} = require('clean-webpack-plugin')
    
      // 配置插件
      plugins: [
        new CleanWebpackPlugin(),
        new HtmlWebpackPlugin({
          title: 'papers-componsing',
          template: './public/index.html'
        })
      ]
    
    • *注意: 目前为止这样安装好的html-webpack-plugin版本是5.3.1
      项目运行时会报错,所以进行了降级,html-webpack-plugin使用4.3.1
    6. 配置loader转译react文件
    npm install --save-dev babel-loader @babel/core @babel/preset-env @babel/polyfill @babel/preset-env @babel/preset-react
    
    7. 新建.babelrc 文件内容如下
    {
      "presets": [
        "@babel/env",
        "@babel/react"
      ]
    }
    
    8. webpack.config.js添加babel-loader
    {
      test: /(\.jsx|\.js)$/,
      use: {
        loader: 'babel-loader',
        options: {
          presets:['@babel/preset-env']
        }
      },
      exclude: /node_modules/
    }
    
    9. cnpm install --save react react-dom

    执行npm start,运行项目后可看到页面上的hello world

    CSS解析配置:

    npm install --save-dev css-loader style-loader sass-loader node-sass file-loader
    
    • *注意: 目前为止这样安装好的sass-loader版本是12.0.0

    项目运行时会报错,所以进行了降级,sass-loader使用10.0.0

    webpack.config.js rules配置如下:

    {
      test: /\.s?[ac]ss$/i,
      use: [
        // 将 JS 字符串生成为 style 节点
        "style-loader",
        // 将 CSS 转化成 CommonJS 模块
        "css-loader",
        // 将 Sass 编译成 CSS
        "sass-loader"
      ]
    },
    {
      test: /\.(png|jpe?g|gif)$/i,
      use: [
        {
          loader: 'file-loader',
          options: {
            name: '[path][name].[ext]',
          }
        },
      ],
    }
    

    eslint解析配置

    npm install --save-dev eslint eslint-loader
    
    npx eslint --init
    
    √ How would you like to use ESLint? · problems
    √ What type of modules does your project use? · esm
    √ Which framework does your project use? · react
    √ Does your project use TypeScript? · Yes
    √ Where does your code run? · browser
    √ What format do you want your config file to be in? · JavaScript
    

    选择完成后会自动生成eslintrc.js文件,并且会安装一些eslint的插件

    要开启或关闭eslint规则就往eslintrc.js的rules里去配置,目前配置了如下规则:

      "rules": { 
        "@typescript-eslint/explicit-module-boundary-types": 0,
        "@typescript-eslint/no-var-requires": 0,
        "@typescript-eslint/no-explicit-any": 0,
        "array-bracket-spacing": [2, "never"],// 是否允许非空数组里面有多余的空格
        "comma-spacing": [2, {"before": false, "after": true}], // 逗号前禁止空格,逗号后要有空格
        "func-call-spacing": 2, // 要求或禁止在函数标识符和其调用之间有空格
        "key-spacing": [2, { "beforeColon": false, "afterColon": true }], // 对象字面量中冒号的前后空格
        // if for while 后都有一个空格
        "keyword-spacing": [2, { "overrides": { "if": { "after": true }, "for": { "after": true }, "while": { "after": true } } }],
        "typescript/no-var-requires": 0,
        "no-var-requires": 0,
        "no-multi-spaces": 2, // 不能有多余的空格
        // 空行最多不能超过1行,在文件结尾处强制执行最大数量的连续空行为1
        "no-multiple-empty-lines": ["error", { "max": 1, "maxEOF": 1 }],
        "prefer-const": 0, // 不校验变量是否被重新分配
        "quotes": [2, "single", "avoid-escape"], // 强制使用一致的反勾号、双引号或单引号
        "semi": [2, "never"], // 代码句尾不能有分号
        "semi-spacing": [2, {"before": false, "after": true}], // 分号前后空格
        "space-before-function-paren": [2, "always"], // 强制在 function的左括号之前使用一致的空格
        "space-infix-ops": ["error", {"int32Hint": false}], // 操作符周围都要有空格
      }
    

    webpack.config.js module的rules第一个添加如下配置

      {
        test: /(\.jsx|\.js)$/,
        exclude: /node_modules/,
        loader: 'eslint-loader',
        enforce: 'pre' // 这里一定要配置,不然一堆报错,而且错误不在自己写的代码里
      }
    

    typescript配置

    .jsx文件名后缀改为.tsx

    npm instal --save typescript @types/react @types/react-dom
    npm install --save-dev awesome-typescript-loader
    // 先不安装 source-map-loader
    
    • *注意:目前为止这样安装好的typescript版本是4.3.2

    项目运行时会报错,所以进行了降级,typescript使用3.3.2

    webpack.config.js的rules添加一项:

    {
      test: /\.tsx?$/,
      loader: 'awesome-typescript-loader'
    },
    {
      test: /(\.tsx?|\.jsx|\.js)$/, // 之前配置的eslint-loader test再加一个tsx的配置
      exclude: /node_modules/,
      loader: 'eslint-loader',
      enforce: 'pre'
    }
    

    webpack.config.js中的extensions修改为 ['.js', '.jsx', '.tsx', '.ts', '.json']

    新建tsconfig.json, 内容如下:

    {
      "compilerOptions": {
        "target": "es5",
        "lib": [
          "dom",
          "dom.iterable",
          "esnext"
        ],
        "allowJs": true,
        "baseUrl": "src",
        "skipLibCheck": true,
        "esModuleInterop": true,
        "allowSyntheticDefaultImports": true,
        "strict": true,
        "forceConsistentCasingInFileNames": true,
        "noFallthroughCasesInSwitch": true,
        "module": "esnext",
        "moduleResolution": "node",
        "resolveJsonModule": true,
        "isolatedModules": true,
        "noEmit": true,
        "jsx": "react",
        "paths": {
          "@/*": [
            "./*"
          ]
        },
        "suppressImplicitAnyIndexErrors": true
      },
      "include": [
        "src"
      ]
    }
    

    引入react路由模块

    1. 安装
    npm install --save react-router-dom @types/react-router-dom
    
    2. 新建页面

    在src/views文件夹下新建两个页面 paper.tsx、my-paper.tsx,里面的内容随便写点

    3.新建router.tsx路由配置文件

    在src/router文件夹下新建router.tsx路由配置文件,内容如下

    import React from 'react'
    import {BrowserRouter as Router, Route, Link} from 'react-router-dom'
    import Paper from '@/views/paper'
    import MyPaper from '@/views/my-paper'
    const ConfigRouter = () => (
      <Router>
        <div>
          <div>
            <Link to="/paper">paper</Link>
            <Link to="/mypaper">my papers</Link>
          </div>
          <div className="m-page-content">
            <Route path="/paper" component={Paper}></Route>
            <Route path="/mypaper" component={MyPaper}></Route>
          </div>
        </div>
      </Router>
    )
    export default ConfigRouter
    
    4. App.tsx文件修改为如下内容
    import React from 'react'
    import '@/css/app.scss'
    import ConfigRouter from './router/router'
    export default class App extends React.Component {
      render () {
        return (
          <ConfigRouter />
        )
      }
    }
    
    5. 页面刷新后404解决

    在webpack.config.js文件中加入如下配置

    module.exports = {
      // ... 此处代码省略
      devServer: {
        historyApiFallback: true
      }
    }
    

    Redux配置

    安装redux react-redux @types/react-redux @types/redux

    cnpm install --save redux react-redux @types/react-redux @types/redux

    Redux具体使用方式见redux在项目中使用

    相关文章

      网友评论

        本文标题:webpack + react + typescript 项目从

        本文链接:https://www.haomeiwen.com/subject/pdxpeltx.html