PHP 后端上的 ReactJS 应用程序 - 如何在本地机器上热重载?

IT技术 reactjs proxy mamp webpack-dev-server livereload
2021-04-27 19:13:26

我正在开发一个由 PHP 后端提供服务的 ReactJS-App。在我的本地机器上,我用一个指向我项目根目录的虚拟主机设置了 MAMP,我使用 webpack 来捆绑我的 React-App。

因为我真的很喜欢使用热重载,所以我现在尝试使用 webpack 开发服务器来代理 MAMP 并从其react热加载功能中受益。

我还没有能够让它工作,我希望有人能帮助我进行配置。或者我的方法基本上不起作用?不管怎样,如果你能帮我解决这个问题,我会很高兴的。提前致谢!到目前为止,这是我的 webpack 配置:

const webpack = require('webpack');
const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const StyleLintPlugin = require('stylelint-webpack-plugin');

module.exports = {
  devtool: 'cheap-module-source-map',
  devServer: {
    port: 3000,
    proxy: {
      '*': {
        target: 'http://my-virtual-host.dev:8888/',
      }
    }
  },
  entry: [
    './src/app.jsx'
  ],
  output: {
    path: path.join(__dirname, 'build'),
    filename: 'bundle.js',
    publicPath: 'http://localhost:3000/build/'
  },
  resolve: {
    extensions: ['.js', '.jsx']
  },
  module: {
    loaders: [
      {
        enforce: 'pre',
        test: /\.jsx?$/,
        include: [
          path.resolve(__dirname, 'src'),
        ],
        loader: 'eslint-loader',
      },
      {
        test: /\.jsx?$/,
        include: [
          path.resolve(__dirname, 'src'),
        ],
        loader: 'react-hot-loader'
      },
      {
        test: /\.jsx?$/,
        include: [
          path.resolve(__dirname, 'src'),
        ],
        loader: 'babel-loader',
      },
      {
        test: /\.css$/,
        use: ExtractTextPlugin.extract({
          use: [
            {
              loader: 'css-loader',
              options: { importLoaders: 1 },
            },
            'postcss-loader',
          ],
        }),
      }
    ]
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoEmitOnErrorsPlugin(),

    new ExtractTextPlugin('bundle.css'),
    new StyleLintPlugin({
      configFile: '.stylelintrc',
      context: 'src',
      files: '**/*.pcss'
    })
  ]
};
1个回答

好的,我找到了解决方案!我的错:我认为我的 webpack 开发服务器应该将每个请求“代理”到 MAMP 并返回其响应。反过来解决我的问题:MAMP 为我的 PHP 应用程序提供服务,而 webpack 开发服务器仅提供其资产。

在开发模式下,我的 PHP 应用程序将资产链接到 webpack 开发服务器(围绕 github 问题的讨论对我帮助很大:https : //github.com/webpack/webpack-dev-server/issues/400)。

现在,我在 webpack 配置中更改的主要属性是:

module.exports = {
  devServer: {
    proxy: {
      '*': {
        target: 'http://my-virtual-host.dev:8888/',
        changeOrigin: true,
      }
    }
  },
  entry: [
    'webpack-dev-server/client?http://localhost:8080/',
    'webpack/hot/only-dev-server', // Enable hot reloading
    './src/app.jsx'
  ],
  output: {
    path: path.join(__dirname, 'build'),
    filename: 'bundle.js',
    publicPath: 'http://localhost:8080/build/'
  },
}

例如http://localhost:8080/build/app.js将资产链接到proxy设置和output.publicPath就可以了。热重载工作正常。

虽然它现在对我有用,但我仍然对你的想法感兴趣!