手机debug模式讲解
看了同事写的一个移动端调试的方案,感觉很好用,总结一下
wepack 自带 移动端调试
wepack 移动端调试 --host 0.0.0.0
npm run start
"start": "webpack serve --host 0.0.0.0"
运行项目直接把本地项目已ip形式代理出去,让手机端也可以访问, 访问地址:http://0.0.0.0/index
存在问题:请求接口需要指定域名请求(可代理域名解决)进化的 debug 模式
在上面的基础上再通过对应服务器(如:test.com )nginx二次转发,把文件请求路径改为本地服务路径
实现方案:
url链接上拼接 ?hmr=1&ip=0.0.0.0 如:http://0.0.0.0/index?hmr=1&ip=0.0.0.0
服务器端nginx做判断 hmr 二次转发,
nginx.config:
...
location ~ ^/app/spa/(.*?)/{
if ( $arg_hmr = 1 ){ // 判断是否启动转发
proxy_pass http://$arg_ip$uri?$args;
#return 302 http://$arg_ip;
break;
}
root /home/site/static/web-static/service;
#return 408;
try_files $uri $uri/ /app/spa/$1/index.html;
}
...
启动本地服务时在文件上引用上拼接 ?hmr=1&ip=0.0.0.0
webpack 插件(plugins)是一个具有 apply 方法的 JavaScript 对象。apply 方法会被 webpack compiler 调用,并且在 整个 编译生命周期都可以访问 compiler 对象
webpack.config:
const MobileDebugPlugin = require('./plugins/MobileDebugPlugin')
...
plugins: [
...
new MobileDebugPlugin(),
...
MobileDebugPlugin:
const internalIp = require('internal-ip')
const qrcode = require('qrcode-terminal')
class MobileDebugPlugin {
apply(compiler) {
if (!process.env.MOBILE_BUG) return
const ip = process.env.LOCAL_IP || internalIp.v4.sync()
// mobileDebug钩子
compiler.hooks.initialize.tap('mobileDebug', () => {
compiler.options.devServer.sockHost = ip
compiler.options.devServer.port = '80'
compiler.options.devServer.host = '0.0.0.0'
compiler.options.output.filename = `js/[name].js?[hash]&hmr=1&ip=${ip}`
compiler.options.output.chunkFilename = `js/[name].js?[hash]&hmr=1&ip=${ip}`
compiler.options.output.hotUpdateChunkFilename = `[id].[fullhash].hot-update.js?hmr=1&ip=${ip}`
compiler.options.output.hotUpdateMainFilename = `[runtime].[fullhash].hot-update.json?hmr=1&ip=${ip}`
for (const rule of compiler.options.module.rules){
if (rule.type === 'asset'){
if (rule.generator.filename.indexOf(ip) === -1){
rule.generator.filename += rule.generator.filename.indexOf('?') > -1 ? `&hmr=1&ip=${ip}` : `?hmr=1&ip=${ip}`
}
}
}
})
compiler.hooks.done.tap('finish', () => {
setTimeout(() => {
console.log('\n')
const url = `http://testn1.dengtacourse.com/app/spa/dengta_activity/index?hmr=1&ip=${ip}`
qrcode.generate(url, {small: true})
console.log('当前处于真机调试模式 \n')
console.log('请扫描二维码,打开链接 \n')
console.log('或者复制链接打开: ' + url)
})
})
}
}
module.exports = MobileDebugPlugin
线上域名引入的带 hmr=1&ip= 的文件都转发到本地
最终实现手机打开:test.com?hmr=1&ip=0.0.0.0 可实时查本地代码 问题解决:所有请求还是指向线上服务器