背景
要在 webpack 打包的前端项目中获取到启动的服务 ip 地址
在webpack的config文件夹下添加获取ip工具方法文件ip.js
const os = require('os');module.exports = () => {let needHost = ''; // 打开的hosttry {// 获得网络接口列表let network = os.networkInterfaces();for (let dev in network) {let iface = network[dev];for (let i = 0; i < iface.length; i++) {let alias = iface[i];if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {needHost = alias.address;}}}} catch (e) {needHost = 'localhost';}return needHost;}
注: os对象是node提供的操作系统对象,可以获取操作系统相关数据
将ip放入webpack导出的全局变量 process.env 中
注: 在 env.js 文件中添加
const ip = require('./ip') // 添加部分 --- 头部引入文件----------------------------------------------function getClientEnvironment(publicUrl) {const raw = Object.keys(process.env).filter(key => REACT_APP.test(key)).reduce((env, key) => {env[key] = process.env[key]return env},{// Useful for determining whether we’re running in production mode.// Most importantly, it switches React into the correct mode.NODE_ENV: process.env.NODE_ENV || 'development',// Useful for resolving the correct path to static assets in `public`.// For example, <img src={process.env.PUBLIC_URL + '/img/logo.png'} />.// This should only be used as an escape hatch. Normally you would put// images into the `src` and `import` them in code to get their paths.PUBLIC_URL: publicUrl,IP: ip() // 添加部分 --- 加入环境变量})// Stringify all values so we can feed into Webpack DefinePluginconst stringified = {'process.env': Object.keys(raw).reduce((env, key) => {env[key] = JSON.stringify(raw[key])return env}, {})}return { raw, stringified }}
项目中使用
console.log('IP',process.env.IP)
