React + Typescript: 开启 HMR/Hot Loader

2022-09-21 10:25:54 浏览数 (1)

  • 参考文献

更新日期: 2020-02-09 "devDependencies": { "react-app-rewire-hot-loader": "^2.0.1", "react-app-rewired": "^2.1.5", "react-hot-loader": "^4.12.19" }, "dependencies": { "react": "^16.12.0", "react-dom": "^16.12.0", "react-router-dom": "^5.1.2", "react-scripts": "3.3.1", "typescript": "~3.7.2" },

Installation

代码语言:javascript复制
yarn add react-app-rewire-hot-loader react-app-rewired react-hot-loader --dev

Usage

config-override

在项目根目录创建一个 config-overrides.js 文件, 是项目的根目录,不是 src 文件夹, 要放到和 package.json 同级。

代码语言:javascript复制
const rewireReactHotLoader = require('react-app-rewire-hot-loader')

/* config-overrides.js */
module.exports = function override (config, env) {
  config = rewireReactHotLoader(config, env)
  return config
}

hot()

然后再跟节点上面执行 hot():

代码语言:javascript复制
// App.js - react-hot-loader >= 4.5.4
import React from 'react'
import { hot } from 'react-hot-loader/root'

const App = () => <div>Hello World!</div>

export default process.env.NODE_ENV === "development" ? hot(App) : App


// For react-hot-loader < 4.5.4, use `hot(module)(App)` instead
// export default process.env.NODE_ENV === "development" ? hot(module)(App) : App

package.json

Replace 'react-scripts' with 'react-app-rewired' in package.json

代码语言:javascript复制
  "scripts": {
    "start": "react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test --env=jsdom",
    "eject": "react-app-rewired eject"
  },

参考文献

  • https://github.com/cdharris/react-app-rewire-hot-loader
  • https://github.com/timarney/react-app-rewired

0 人点赞