Skip to content

Commit

Permalink
feat(webpack-runner): dev-server配置host为0.0.0.0时, 默认以本地ip打开 (#4699)
Browse files Browse the repository at this point in the history
  • Loading branch information
Liaozzzzzz authored and Littly committed Oct 28, 2019
1 parent ecc1557 commit 6bd7884
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 4 deletions.
10 changes: 8 additions & 2 deletions packages/taro-webpack-runner/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import buildConf from './config/build.conf'
import devConf from './config/dev.conf'
import baseDevServerOption from './config/devServer.conf'
import prodConf from './config/prod.conf'
import { addLeadingSlash, addTrailingSlash, recursiveMerge } from './util'
import { addLeadingSlash, addTrailingSlash, recursiveMerge, formatOpenHost } from './util'
import { bindDevLogger, bindProdLogger, printBuildError } from './util/logHelper'
import { BuildConfig } from './util/types'
import { makeConfig } from './util/chain';
Expand Down Expand Up @@ -121,7 +121,13 @@ const buildDev = async (appPath: string, config: BuildConfig): Promise<any> => {

/* 补充处理devServer.open配置 */
if (devServerOptions.open) {
opn(devUrl)
const openUrl = formatUrl({
protocol: devServerOptions.https ? 'https' : 'http',
hostname: formatOpenHost(devServerOptions.host),
port: devServerOptions.port,
pathname
})
opn(openUrl)
}
})
})
Expand Down
31 changes: 29 additions & 2 deletions packages/taro-webpack-runner/src/util/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import * as path from 'path'
import { mergeWith } from 'lodash';
import { mergeWith } from 'lodash'
import { networkInterfaces } from 'os'

const isEmptyObject = function (obj) {
if (obj == null) {
Expand Down Expand Up @@ -61,6 +62,31 @@ const isNpmPackage = (name: string) => !/^(\.|\/)/.test(name)
const addLeadingSlash = (url: string) => url.charAt(0) === '/' ? url : '/' + url
const addTrailingSlash = (url: string) => url.charAt(url.length - 1) === '/' ? url : url + '/'

const formatOpenHost = host => {
let result = host
// 配置host为0.0.0.0时,可以转换为ip打开, 其他以配置host默认打开
if (result === '0.0.0.0') {
// 设置localhost为初值, 防止没正确获取到host时以0.0.0.0打开
result = 'localhost'
const interfaces = networkInterfaces()
for (const devName in interfaces) {
const isEnd = interfaces[devName].some(item => {
// 取IPv4, 不为127.0.0.1的内网ip
if (item.family === 'IPv4' && item.address !== '127.0.0.1' && !item.internal) {
result = item.address
return true
}
return false
})
// 若获取到ip, 结束遍历
if (isEnd) {
break
}
}
}
return result
}

export {
emptyObj,
emptyTogglableObj,
Expand All @@ -71,5 +97,6 @@ export {
formatTime,
recursiveMerge,
addLeadingSlash,
addTrailingSlash
addTrailingSlash,
formatOpenHost
}

0 comments on commit 6bd7884

Please sign in to comment.