分享:移动端测试让 webpack-dev-server 启动后显示二维码

2018-05-24 00:42:41 +08:00
 vevlins

因为要做移动端测试,所以经常执行一串操作。

最近看到 rax-scripts 自己带了命令行输出二维码的操作,觉得也可以自己来实现这个功能。

做了一个很简单的 webpack 插件分享给大家看实现,非常简单,也可以自己实现。 webpack-server-qrcode

使用

var serverQRcode = require('webpack-server-qrcode');

{
  ...
  plugins:[
    new serverQRcode()
  ]
}

原理

基于 qrcode-terminal-alpha 这个包在命令行下显示二维码。通过 os.networkInterfaces 获取 ip。通过 compiler.options.devServer.port 获取 webpack-dev-server 配置的端口号。

const qrcode = require('qrcode-terminal-alpha');
const os = require('os');

module.exports = class serverQRcode {
  constructor(options) {
      this.options = options;
      this.qrcode = qrcode;
  }
  
  getIp(){
      const ifaces = os.networkInterfaces();
      let ips = [];
      for (const key in ifaces) {
        if (ifaces.hasOwnProperty(key)) {
          const nets = ifaces[key];
          nets.forEach(net=>{
            if(net.family === 'IPv4'){
              const address = net.address;
              ips.push(address);
            }
          })
        }
      }
      return ips;
    }

  printQRcode(url){
    this.qrcode.generate(url,{small:true},(qrcode)=>{
      console.log(qrcode);
      console.log(url);
    })
  }
  apply(compiler) {
    const port = compiler.options.devServer.port;
    const ips = this.getIp();
    ips.forEach(ip=>{
      const url = `http://${ip}:${port}`;
      this.printQRcode(url);
    })
  }
};

显示

1481 次点击
所在节点    前端开发
1 条回复
woscaizi
2018-05-24 01:15:12 +08:00
炫酷

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/457306

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX