Webpack 4热重装无法与React TypeScript一起使用

时间:2019-05-25 10:23:41

标签: reactjs typescript webpack webpack-dev-server

我正在使用自定义Webpack配置使用Typescript设置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;

这是我在控制台中看到的: enter image description here

编辑(已解决):

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

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

相反: import App from './Components/App';

感谢大家的帮助!

3 个答案:

答案 0 :(得分:1)

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

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

days <- function(data) {
  on_day <- strsplit(data, "on day ")[[1]][2]
  num <- strsplit(on_day, " ")[[1]][1]
  as.numeric(unlist(strsplit(num, ",")))
}

strg1 <- 'At 08:00 AM, on day 4 of the month, every 12 months'
strg2 <- 'At 08:00 AM, on day 4,20,2 of the month, every 12 months'

# Sample output
days(strg1)
[1] 4

days(strg2)
[1] 4 20 2

答案 1 :(得分:0)

请确保在这样的插件部分中包含HotModuleReplacementPlugin

const webpack = require('webpack');

plugins: [
new HtmlWebpackPlugin({
  template: './application/src/index.html'
 }),
 new webpack.HotModuleReplacementPlugin()
],

要解决热装问题,请将内容库设置为源目录并启用内联模式

webpack-dev-server --inline

答案 2 :(得分:0)

尝试一下,writeToDisk很重要:

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