2017-08-12 93 views
0

我正在使用NextJs构建应用程序。我有两个用于生产和开发的不同URL,我想访问客户端环境的相应URL。我跟着这guide但我的PROCESS.ENV.API_URL在开发中是空的。nextjs的生产URL

这里是我的文件:

.ENV:

API_URL=https://my-staging-url.com 

.env.production:

API_URL=https://my-production-url.com 

.babelrc:

{ 
    "presets": [ 
    "next/babel" 
    ], 
    "env": { 
    "development": { 
     "plugins": ["inline-dotenv"] 
    }, 
    "production": { 
     "plugins": ["transform-inline-environment-variables"] 
    } 
    } 

}

环境变量的用法:

import 'isomorphic-fetch'; 

export const SET_QUERY = 'SET_QUERY'; 
export const CLEAR_SEARCH = 'CLEAR_SEARCH'; 
export const START_FETCHING_SEARCH = 'START_FETCHING_SEARCH'; 
export const SET_SEARCH_RESULTS = 'SET_SEARCH_RESULTS'; 
export const FETCHING_SEARCH_FAILED = 'FETCHING_SEARCH_FAILED'; 

export const getSearch = value => { 
    const url = `${process.env.API_URL}search?q=${value}`; // THIS IS EMPTY 
    console.log(url); 
    return fetch(url); 
}; 

// Implement search action 
export const doSearch = query => dispatch => { 
    dispatch({ type: START_FETCHING_SEARCH }); 
    return dispatch => { 
     return getSearch(query).then(response => { 
      dispatch({ type: SET_SEARCH_RESULTS }); 
     },() => { 
      dispatch({ type: FETCHING_SEARCH_FAILED }); 
     }); 
    }; 
}; 

export const clearSearch =() => dispatch => { 
    return dispatch({ type: CLEAR_SEARCH }) 
}; 

希望帮助,干杯!

回答

0

你意有所指忘了安装插件

简单,你可以在你的包JSON文件复制粘贴此:

"dependencies": { 
    "next": "latest", 
    "react": "^15.4.2", 
    "react-dom": "^15.4.2", 
    "babel-plugin-inline-dotenv": "^1.1.1", 
    "babel-plugin-transform-inline-environment-variables": "^0.1.1" 
    } 

和运行 npm install

,或者你可以运行 npm install babel-plugin-inline-dotenv babel-plugin-transform-inline-environment-variables --save -dev

或者您可以根据这个简单地实现这个功能引导with-universal-configuration

.bablerc

{ 
"plugins":[ 
    ["transform-define", "./env-config.js"] 
] 
} 

.ENV-config.js

const prod = 'production' === process.env.NODE_ENV 

module.exports = { 
    'process.env.API_URL': prod ? 'http://api.dev.com' : 'http://api.local.com/', 
} 

和包装JSON你应该已经安装babel-plugin-transform-define