使用开发服务器时,Webpack不会将文件发送到index.html

时间:2020-03-14 14:30:43

标签: reactjs typescript webpack webpack-dev-server

我一直在尝试设置webpack并使用没有CRA行话的打字稿进行反应。开发服务器不会将文件发送到index.html文件以在浏览器中进行查看。弹出时的CRA模板具有用于构建和开发模式的多个js脚本,但我想忽略这一点,并保持结构尽可能干净和简单

Package.json-

  "scripts": {
    "start": "webpack-dev-server --mode development --open --hot",
    "build": "webpack --mode production"
  }

webpack配置-

const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin')
const CompressionPlugin = require('compression-webpack-plugin')
const HtmlWebpackChangeAssetsExtensionPlugin = require('html-webpack-change-assets-extension-plugin')

module.exports = {
  entry: {
    app: path.resolve(__dirname, 'src/index.tsx')
  },

  output: {
    path: path.resolve(__dirname, 'dist'),
    chunkFilename: '[name].[hash].chunk.js',
    publicPath: '/codestage'
  },

  devtool: 'source-map',
  resolve: {
    extensions: ['.ts', '.tsx', '.js']
  },

  module: {
    strictExportPresence: true,
    rules: [
      {
        test: /\.js$/,
        loader: require.resolve('babel-loader'),
        exclude: /node_modules/,
        options: {
          compact: true
        }
      },
      {
        test: /\.tsx?$/,
        include: path.join(__dirname, 'src'),
        exclude: /node_modules/,
        use: [
          { loader: 'babel-loader' },
          {
            loader: 'ts-loader',
            options: {
              transpileOnly: true
            }
          }
        ]
      },

      { enforce: 'pre', test: /\.js$/, loader: 'source-map-loader' }
    ]
  },

  plugins: [
    new HtmlWebpackPlugin({
      template: './index.html',
      jsExtension: '.gz',
      filename: './index.html'
    }),
    new CompressionPlugin({
      test: /\.js(\?.*)?$/i,
      deleteOriginalAssets: true
    }),
    new ForkTsCheckerWebpackPlugin({ eslint: true }),
    new HtmlWebpackChangeAssetsExtensionPlugin()
  ],

  optimization: {
    runtimeChunk: 'single',
    splitChunks: {
      cacheGroups: {
        vendor: {
          reuseExistingChunk: true,
          test: /[\\/]node_modules[\\/]/,
          name: 'vendor',
          chunks: 'initial'
        }
      }
    }
  }
}

index.html

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

目录结构-

Directory Structure

HTML在浏览器中检查-

Html inspect in browser

如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

实际上,开发服务器是开发和调试的工具。所有内容都内置在内存中。您可以尝试使用npm run build脚本来发出可用于部署的文件。