Reputation: 39018
I am passing in NODE_ENV
variables into my webpack.config
from package.json
in order to return an object that either contains API endpoints for localhost or production.
"scripts": {
"dev": "NODE_ENV=development webpack-dev-server --history-api-fallback",
"prod": "NODE_ENV=production webpack -p",
"build": "NODE_ENV=production webpack -p"
}
function endpoints(env) {
let prefix = env === 'development' ? 'http://localhost' : '';
return {
"login": `${prefix}/app/api/login`
}
}
module.exports = endpoints;
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,
// ....
Here below I can see the console.log
of the const api
.
Now my question is, how do I now generate or export out an actual file api
to be used inside of my src/services/api
file:
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));
};
Upvotes: 1
Views: 235
Reputation: 7767
I think this is an XY problem. You could generate the files with a bit of Node (something like fs.writeFileSync('api.js', contents)
, or you could do it with a bit of shell scripting, but you could also just use env
in your code using DefinePlugin (example: new webpack.DefinePlugin({ env: JSON.stringify(process.env.NODE_ENV) })
. Then you'd be able to access env
in your code directly.
Upvotes: 3