前言
opn模块通常是作为跨平台的打开文件或者网站的模块,在web应用中最常见的使用是比如项目开发或者启动的时候打开浏览器进行访问。
优点
模块地址
https://npm.taobao.org/package/opn
基本使用
安装
npm install opn
使用
const opn = require(‘opn‘); //Opens the image in the default image viewer opn(‘unicorn.png‘).then(()=>{ //image viewer closed }); //Opens the url in the default browser opn(‘http://sindresorhus.com‘); //Specify the app to open in opn(‘http://sindresorhus.com‘,{app:‘firefox‘}); //Specify app arguments opn(‘http://sindresorhus.com‘,{app:[‘google chrome‘,‘--incognito‘]})
api
目标
类型为字符串。目标通常为你想打开的文件、url或者可执行的文件,一般会用系统中默认的应用打开,当然也可以指定应用以及相关的开启参数。
配置项
类型为对象,object。
实践
自己在本地写一个demo,可以实现这个模块的使用,在使用的时候大家要注意我们除了常规的gulp调用模块只为也可以直接用npm工作流来实现我们的需求,在根目录下新建scripts文件夹,写对应的功能js文件,然后在package.json中直接node执行这个文件即可
//package.json "scripts": { "test":"teset", "opn":"gulp", "opn2":"node ./scripts/opn" }
//gulpfile.js let gulp = require(‘gulp‘) let opn = require(‘opn‘) let os = require(‘os‘) let uri = "http://www.baidu.com" gulp.task("default",function(){ let osStr = os.platform() if(osStr.indexOf("win") > -1){ opn(uri,{ app:[‘chrome‘] }) } })
//opn.js let opn = require("opn") let is = require("os") let osStr = os.platform() let uri = "http://www.baidu.com" if(osStr.indexOf("win") > -1){ opn(uri,{app:[‘chrome‘]}) };
更多探索
我们知道默认的weback也可以通过dev-server来实现启动浏览器和服务,我们看下它是否也是以来这个模块来实现的呢?
在webpack-dev-server的模块中,生产以来中,我们如愿找到了opn的模块依赖,顺便扒一下源代码,webpack-dev-server,我们找到了opn模块的引入以及其对应的使用
const open = require(‘opn‘); if(PushSubscriptionOptions.open){ let openOptions = {}; let openMessage = ‘Unable to open browser‘; if(typeof PushSubscriptionOptions.open === ‘string‘){ openOptions = {app: PushSubscriptionOptions.open}; openMessage += `:${options.open}`; } open(uri + (options.openPage || ‘‘), openOptions).catch(()=>{ console.log(`${openMessage}.If you are running in a headless environment, please do not use the open flag.`); }) }
代码分析
原文:https://www.cnblogs.com/tommymarc/p/12120002.html