【问题标题】:Webpack 4 hot reload not working with React TypeScriptWebpack 4 热重载不适用于 React TypeScript
【发布时间】:2019-10-11 17:20:15
【问题描述】:

我正在使用 Typescript 使用自定义 Webpack 配置设置 React 应用程序,但我遇到了热重载问题。

仅当我重新启动应用程序时才会显示更改。

我寻找答案和示例,但找不到对我有帮助的解决方案。

下面是我的代码和配置。

package.json

{
  "name": "frontend-bootstrap-project",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "webpack-dev-server --mode development  --open --hot",
    "build": "webpack --mode production"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "awesome-typescript-loader": "^5.2.1",
    "eslint": "^5.16.0",
    "html-webpack-plugin": "^3.2.0",
    "redux": "^4.0.1",
    "redux-saga": "^1.0.2",
    "typescript": "^3.4.5",
    "webpack": "^4.32.2",
    "webpack-cli": "^3.3.2",
    "webpack-dev-server": "^3.4.1"
  },
  "dependencies": {
    "@types/react": "^16.8.18",
    "@types/react-dom": "^16.8.4",
    "@typescript-eslint/parser": "^1.9.0",
    "eslint-plugin-react": "^7.13.0",
    "react": "^16.8.6",
    "react-dom": "^16.8.6",
    "ts-loader": "^6.0.1"
  }
}

webpack.config.json

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: ["./application/src/index.tsx"],
  resolve: {
    extensions: [".ts", ".tsx", ".js"]
  },
  output: {
    path: path.join(__dirname, './application/dist'),
    filename: 'bundle.min.js'
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        loader: 'awesome-typescript-loader'
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './application/src/index.html'
    })
  ]
};

App.tsx

import * as React from 'react';

class App extends React.Component {
  render() {
    return (
      <div>
        <h1>Welcome to React with Typescript</h1>
      </div>
    );
  }
}

export default App;

这是我在控制台中得到的:

编辑(已解决):

我上面的代码正在运行。 我在 index.tsx 文件中发现了错字。

它是: import App from './components/App';

改为: import App from './Components/App';

感谢大家的帮助!

【问题讨论】:

    标签: reactjs typescript webpack webpack-dev-server


    【解决方案1】:

    试试这个,writeToDisk 很重要:

        devServer: {
        contentBase: path.resolve(__dirname, './application/dist'),
        host: 'localhost',
        hot: true,
        writeToDisk: true
    }
    

    【讨论】:

      【解决方案2】:

      要解决此问题,您需要使用devServer

      在您的情况下,将其添加到您的 webpack 配置中:

       devServer: {
          contentBase: path.join(__dirname, './application/dist'),
          compress: true,
          port: 9000
        }
      

      【讨论】:

      • 不,它没有帮助。在描述中,我添加了我在控制台中得到的图片。
      • 尝试将path.join(__dirname, './application/dist') 替换为path.join(__dirname, 'application/dist') 以用于contentBaseoutput
      • 也无济于事。
      猜你喜欢
      • 2019-05-29
      • 2018-09-15
      • 2021-08-03
      • 2020-11-24
      • 2020-12-18
      • 1970-01-01
      • 2016-05-13
      • 2019-05-20
      • 1970-01-01
      相关资源
      最近更新 更多