如何创build/生成/从我的webpack 2configuration文件导出用于我的React代码里面?

我将NODE_ENVvariables传递到package.json webpack.config中,以便返回包含localhost或production的API端点的对象。

1)package.json

 "scripts": { "dev": "NODE_ENV=development webpack-dev-server --history-api-fallback", "prod": "NODE_ENV=production webpack -p", "build": "NODE_ENV=production webpack -p" } 

2)endpoints.js

 function endpoints(env) { let prefix = env === 'development' ? 'http://localhost' : ''; return { "login": `${prefix}/app/api/login` } } module.exports = endpoints; 

3)webpack.config

 const webpack = require('webpack') const HtmlWebpackPlugin = require("html-webpack-plugin"); const ExtractTextPlugin = require("extract-text-webpack-plugin"); const CopyWebpackPlugin = require("copy-webpack-plugin"); const path = require("path"); const dist = path.resolve(__dirname, "dist"); const src = path.resolve(__dirname, "src"); const endpoints = require("./src/endpoints"); const api = endpoints(process.env.NODE_ENV); console.log('webpack api', api); module.exports = { context: src, entry: [ "./index.js" ], output: { path: dist, // .... 

下面我可以看到const apiconsole.log

在这里输入图像说明


现在我的问题是,我现在如何生成或导出一个实际的文件api用于我的src/services/api文件里面:

 import axios from 'axios' // import api from '../../webpack.config' <-- ? // import api from '../../api.js <-- ? const log = (method, err) => { console.error(`%c${method}`, 'background: #393939; color: #F25A43', err); return null; }; export const userLogin = (username, password) => { const post_data = { username, password }; return axios.post('http://localhost/app/api/login', post_data) // <-- api to be used here .then(res => res) .catch((err) => log('api.userLogin', err)); }; 

我认为这是一个XY问题 。 你可以用一些Node来生成文件(比如fs.writeFileSync('api.js', contents) ,或者你可以用一些shell脚本来做,但是你也可以在你的代码中使用env来使用DefinePlugin (例如: new webpack.DefinePlugin({ env: JSON.stringify(process.env.NODE_ENV) }) 。然后你就可以直接访问你的代码了。