Leon Gaban
Leon Gaban

Reputation: 39044

How to setup Webpack to change a specific config file for dev or production?

I have 2 files, config_local.js and config_prod.js.

How would you pass in a variable into webpack to basically generate a new file named config_api.js from either the local one or the production one.

config_local.js

"api": {
  "login": "http://localhost/app/api/login/",
  "users": "http://localhost/app/api/users/"
}

config_prod.js

"api": {
  "login": "/app/api/login/",
  "users": "/app/api/users/"
}

Then inside of my services/api.js file

import axios from 'axios'

export const userLogin = (username, password) => {
    const post_data = { username, password };
    return axios.post('http://localhost/app/api/login', post_data)
        .then(res => res);
};

I could do something like so:

import axios from 'axios'
import api from 'config_api' 

export const userLogin = (username, password) => {
    const post_data = { username, password };
    return axios.post(api.login, post_data)  // <--
        .then(res => res);
};

Upvotes: 3

Views: 1079

Answers (1)

owais
owais

Reputation: 4922

In package.json you can use scripts or even at commandline you can use environment variable.s

 "scripts": {
    "dev": "NODE_ENV=development webpack",
    "production": "NODE_ENV=production webpack",
    "watch": "npm run dev -- --watch"
  },

In webpack.config.js you can use

const inProduction = process.env.NODE_ENV === 'production';
const inDevelopment = process.env.NODE_ENV === "development";


if(inProduction) 
//do this
if(inDevelopment)
//do that

webpack by default looks for weback.config.js however for custom config you can use webpack --config config_local.js

Upvotes: 2

Related Questions