1.next.config.js
const withImages = require('next-images')
const isDevMode=process.env.NODE_ENV === 'development'
const serverBaseUrl=isDevMode ? 'http://localhost:8080/myserver':'http://192.168.100.123:8080/myserver'
const serverApiUrl=isDevMode ? 'http://localhost:8080/myserver/api':'http://192.168.100.123:8080/myserver/api'
const nextConfig={
serverRuntimeConfig:{//这里的配置项只能在服务端获取到,在浏览器端是获取不到的
//todo server
},
publicRuntimeConfig: {//这里的配置既可以服务端获取到,也可以在浏览器端获取到
serverBaseUrl:serverBaseUrl,
serverApiUrl: serverApiUrl,
}
}
module.exports = withImages(nextConfig)
2.在页面或者组件中获取变量方式
import axios from 'axios'
import getConfig from 'next/config'
const {serverBaseUrl, serverApiUrl} = getConfig().publicRuntimeConfig
axios.defaults.baseURL=serverApiUrl;