Monday 5 June 2017

How to create/generate/export a file from my webpack 2 config to be used inside of my React code?

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.

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,
    // ....


Here below I can see the console.log of the const api.

enter image description here


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));
};



via Leon Gaban

No comments:

Post a Comment