我已经尝试了一周,但是我还没有能够让三个东西一起工作。如果有人可以帮助我解决这个问题,我将永远感激不尽,因为我浪费了很多时间。
问题:
如果我代理myserver.dev,热重载会出现404错误。更改publicPath无效。我将URL附加到webpack-hot-middleware/client,它可以修复路径,但是HMR文件最终在控制台中出现“GET”错误,并且没有任何信息。如果我只使用HTML并忽略任何PHP/MAMP,则热重载正常工作。总的来说,我非常困惑,可能错过了一个简单的概念。
我正在尝试让它们一起工作的内容:
- Wordpress用于其REST API
- React用于视图和UI
- MAMP用于本地主机和MySQL
- BrowserSync用于跨设备测试
- Webpack用于编译和热重载
这是我使用的样板: https://github.com/Browsersync/recipes/tree/master/recipes/webpack.react-hot-loader
主题目录结构:
-/inc
-/src
--/components
--/containers
--/styles
--app.js
-bundle.js
-functions.php
-index.php
-package.json
-server.js
-style.css
-webpack.config.js
我尝试了无数种配置,所以为了简单起见,我将下面的代码清空了。
webpack.config.js:
var webpack = require('webpack');
var path = require('path');
module.exports = {
context: path.join(__dirname, 'src'),
entry: [
'webpack/hot/dev-server',
'webpack-hot-middleware/client',
'./app'
],
output: {
path: __dirname,
publicPath: __dirname,
filename: 'bundle.js'
},
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
module: {
loaders: [
{ test: /\.jsx?$/, exclude: /node_modules/, loaders: ['react-hot', 'babel'] }
]
}
};
server.js:
/**
* Require Browsersync along with webpack and middleware for it
*/
var browserSync = require('browser-sync');
var webpack = require('webpack');
var webpackDevMiddleware = require('webpack-dev-middleware');
var webpackHotMiddleware = require('webpack-hot-middleware');
/**
* Require ./webpack.config.js and make a bundler from it
*/
var webpackConfig = require('./webpack.config');
var bundler = webpack(webpackConfig);
/**
* Run Browsersync and use middleware for Hot Module Replacement
*/
browserSync({
proxy: {
target: 'http://myserver.dev',
middleware: [
webpackDevMiddleware(bundler, {
// IMPORTANT: dev middleware can't access config, so we should
// provide publicPath by ourselves
publicPath: webpackConfig.output.publicPath,
// pretty colored output
stats: { colors: true }
// for other settings see
// http://webpack.github.io/docs/webpack-dev-middleware.html
}),
// bundler should be the same as above
webpackHotMiddleware(bundler)
]
},
// prevent opening a new window.
open: false,
// no need to watch '*.js' here, webpack will take care of it for us,
// including full page reloads if HMR won't work
files: [
]
});
package.json:
{
"main": "server.js",
"scripts": {
"build": "webpack",
"start": "node ."
},
"dependencies": {
"babel-core": "^5.8.9",
"babel-loader": "^5.3.2",
"browser-sync": "^2.8.0",
"react": "^0.13.3",
"react-hot-loader": "^1.2.8",
"webpack": "^1.10.5",
"webpack-dev-middleware": "^1.2.0",
"webpack-hot-middleware": "^1.1.0"
}
}
publicPath
指定了在浏览器中引用输出文件时的公共 URL 地址。__dirname
在这里是错误的,应该是类似于http://localhost:3000
的东西。查看文档。 - dotcs