首页 > 解决方案 > 为什么我的 React 应用程序只在没有缓存的情况下刷新加载?

问题描述

似乎这会更简单,但我很难过。我的 React 应用程序正在使用 Webpack 提供服务,如果我在隐身浏览器中打开 localhost(或刷新没有缓存的常规选项卡),内容就会出现。但否则我会在我的检查员中收到这些错误:

在此处输入图像描述

在此处输入图像描述

src/index.jspublic/index.html文件就像一个基本的 Create React App 配置,像这样:

src/index.js:

import React from 'react';
import ReactDOM from "react-dom";
import App from "./components/App";

ReactDOM.render(<App />, document.getElementById('root'));

公共/index.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Index</title>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>

Webpack如下:

const Dotenv = require('dotenv-webpack')
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')

const config = {
  entry: './src/index.js',
  output: {
    filename: 'bundle.js'
  },
  resolve: {
    extensions: ['.ts', '.tsx', '.js', '.jsx', '.css']
  },
  module: {
    rules: [
      {
        test: /\.(tsx?|jsx?)$/,
        exclude: /node_modules/,
        use: [
          {
            loader: 'babel-loader',
            options: {
              rootMode: 'upward'
            }
          }
        ]
      },
      {
        enforce: 'pre',
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'source-map-loader'
      },
      {
        test: /\.(png|svg|jpg|gif)$/,
        use: [
          {
            loader: 'url-loader'
          }
        ]
      },
      {
        test: /\.(woff|woff2|eot|ttf|otf)$/,
        use: ['file-loader']
      }
    ]
  },
  node: {
    fs: 'empty'
  },
  plugins: [
    new Dotenv({
      path: './.env',
      systemvars: true
    }),
    new ForkTsCheckerWebpackPlugin({ eslint: true })
  ]
}

module.exports = env => {
  const styleRule = {
    test: /\.(scss|css)$/,
    use: ['style-loader', 'css-loader', 'sass-loader']
  }

  const htmlPluginConfig = { template: 'public/index.html', inject: true }
  config.module.rules.push(styleRule)
  config.plugins.push(new HtmlWebpackPlugin(htmlPluginConfig))
  config.devtool = 'inline-source-map'
  config.devServer = {
    contentBase: './src',
    overlay: true,
    port: 8080
  }
  return config
}

我知道有东西被顶住了,但我不能把手指放在上面。

标签: javascriptreactjswebpack

解决方案


推荐阅读