Tuesday, 6 June 2017

How to import javascript export file generated from the webpack.config?

Problem description

I need to set the DEV or Production environment so I can test API's either locally or get them ready for production.

ie: Either use http://localhost/api/app/login or /api/app/login

Now I was able to accomplish this by attaching NODE_ENV variables to my npm scripts in the package.json and a couple of lines of code in my webpack.config as so:

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

webpack.config

const environment = process.env.NODE_ENV;
....
new CopyWebpackPlugin([{ from: "static" }])

^ that will create an env I can use in my services/api.js file. Now my Problem is that my Jest tests will fail every time because env is undefined.

Attempted solution - need help

So now instead what I'm trying to do is use node to actually generate a Javascript file that I can actually import directly into my services/api.js that way I avoid the undefined env error in testing.

I'm able to create a Javascript file with the following updates to my webpack.config

const fs = require('fs');
const webpack = require('webpack')
const environment = process.env.NODE_ENV;

// fs.writeFileSync('src/consts/env.txt', environment);

const stream = fs.createWriteStream("src/consts/endpoints.js");
stream.once('open', function(fd) {
  stream.write('export const environment = () => "'+environment+'"');
  stream.end();
});

The file it created (src/consts/endpoints.js):

export const environment = () => "development"

Now my updated services/api.js

import axios from 'axios'
import environment from '../consts/endpoints'
console.log('api.js environment:', environment);

However environment is undefined when I check out localhost. enter image description here


How can I fix this problem? Is it a race condition? Is there another way to generate the file I need to import?

I tried to generate a .txt file however I can't import that file locally, can only do it in the cloud.



via Leon Gaban

No comments:

Post a Comment