背景

要在 webpack 打包的前端项目中获取到启动的服务 ip 地址

在webpack的config文件夹下添加获取ip工具方法文件ip.js

  1. const os = require('os');
  2. module.exports = () => {
  3. let needHost = ''; // 打开的host
  4. try {
  5. // 获得网络接口列表
  6. let network = os.networkInterfaces();
  7. for (let dev in network) {
  8. let iface = network[dev];
  9. for (let i = 0; i < iface.length; i++) {
  10. let alias = iface[i];
  11. if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
  12. needHost = alias.address;
  13. }
  14. }
  15. }
  16. } catch (e) {
  17. needHost = 'localhost';
  18. }
  19. return needHost;
  20. }

注: os对象是node提供的操作系统对象,可以获取操作系统相关数据

将ip放入webpack导出的全局变量 process.env 中

注: 在 env.js 文件中添加

  1. const ip = require('./ip') // 添加部分 --- 头部引入文件
  2. ----------------------------------------------
  3. function getClientEnvironment(publicUrl) {
  4. const raw = Object.keys(process.env)
  5. .filter(key => REACT_APP.test(key))
  6. .reduce(
  7. (env, key) => {
  8. env[key] = process.env[key]
  9. return env
  10. },
  11. {
  12. // Useful for determining whether we’re running in production mode.
  13. // Most importantly, it switches React into the correct mode.
  14. NODE_ENV: process.env.NODE_ENV || 'development',
  15. // Useful for resolving the correct path to static assets in `public`.
  16. // For example, <img src={process.env.PUBLIC_URL + '/img/logo.png'} />.
  17. // This should only be used as an escape hatch. Normally you would put
  18. // images into the `src` and `import` them in code to get their paths.
  19. PUBLIC_URL: publicUrl,
  20. IP: ip() // 添加部分 --- 加入环境变量
  21. }
  22. )
  23. // Stringify all values so we can feed into Webpack DefinePlugin
  24. const stringified = {
  25. 'process.env': Object.keys(raw).reduce((env, key) => {
  26. env[key] = JSON.stringify(raw[key])
  27. return env
  28. }, {})
  29. }
  30. return { raw, stringified }
  31. }

项目中使用

  1. console.log('IP',process.env.IP)