webpack-hot-middleware热加载相关错误的解决办法

错误1:找不到__webpack_hmr

GET http://127.0.0.1/__webpack_hmr 404 (Not Found)

在webpack的entry配置添加引用路径’webpack-hot-middleware/client?path=/__webpack_hmr&timeout=10000&reload=true’,相关的参数最好不要省略,否则会出现无法自动刷新的问题。处理脚本如下:

//  准备webpack配置信息
let hotMiddlewareScript = 'webpack-hot-middleware/client?path=/__webpack_hmr&timeout=10000&reload=true',
    wpConfig = require('./webpack.config'),
    //  准备修改配置信息
    entries = Object.keys(wpConfig.entry)

//  添加热加载信息
entries.forEach((key) => {
    wpConfig.entry[key].push(hotMiddlewareScript);
})

//  添加插件信息
if(wpConfig.plugins === undefined) {
    wpConfig.plugins = []
}

//  添加热加载插件
wpConfig.plugins.push(
     new webpack.optimize.OccurrenceOrderPlugin(),
     new webpack.HotModuleReplacementPlugin(),
     new webpack.NoEmitOnErrorsPlugin())

错误2:找不到hot-update.json

main.bundle.js:30 GET http://127.0.0.1/static/44588e3474a86cea5670.hot-update.json 404 (Not Found)

webpack配置中的publicPath必须是绝对地址,详细配置如下所示:

module.exports = {
    //  其他配置信息略
    // ……
    output : {
        path: configs.dist,
        //  必须是绝对地址
        publicPath: 'http://127.0.0.1/static/',
        filename : '[name].bundle.js',
        libraryTarget : 'var'        
    }
}

错误3:No ‘Access-Control-Allow-Origin’ header

XMLHttpRequest cannot load http://127.0.0.1/static/df222441abc9ddb6a616.hot-update.json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.

不可思议,在本地访问竟然会出现AJAX跨域问题,仔细检查后发现,浏览器把localhost与127.0.0.1当成了两个不同的域,解决的方法很多,只说最简单的一种,访问应用时,尽量采用与webpack配置中的publicPath完全一致的路径,如在本文中,最好的访问方法是输入http://127.0.0.1/访问本地应用。

错误4:OccurenceOrderPlugin构造器错误

new webpack.optimize.OccurenceOrderPlugin(),
TypeError: webpack.optimize.OccurenceOrderPlugin is not a constructor
    at Object.<anonymous> (E:\Workspace\vue-hot\dev-server.js:23:6)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:394:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:509:3

此问题一般出现在webpack 2中,解决办法很简单,将OccurenceOrderPlugin改为OccurrenceOrderPlugin即可。

总结

webpack编译程序有两种热加载方式,webpack-dev-server与webpack-hot-middleware方式,从webpack 2的性能来看,webpack-dev-server完全能够满足开发的需要,但最大的问题在于,webpack-dev-server不能向外发布服务,只能在本地访问。

你可能感兴趣的:(项目构建)