timarney / react-app-rewired

Override create-react-app webpack configs without ejecting
MIT License
9.79k stars 425 forks source link

Need help regarding dotenv-webpack integration to this package #512

Closed handhikadj closed 3 years ago

handhikadj commented 3 years ago

the goal is I don't want to prefix my .env file with REACT_APP_ how do I define the plugin?

config-overrides.js :

const Dotenv = require('dotenv-webpack');

module.exports = (config) => {
    require('react-app-rewire-postcss')(config, {
        plugins: (loader) => [require('postcss-rtl')()],
    });

    config.plugins.push(new Dotenv());

    console.log(config.plugins); // logs shown below

    return config;
};
DefinePlugin {
    definitions: {
      'process.env.API_BASEURL': '"http://myapi.test"',
      'process.env': '{}'
    }
  }

I want to get the definitions of the DefinePlugin so I can start using process.env.API_BASEURL every where in my code. how do I do that?

dawnmist commented 3 years ago

I believe you need to push the DefinePlugin into the config.plugins array, so that webpack can use it. i.e.:

const webpack = require('webpack');

module.exports = (config) => {
  ...
  config.plugins.push(
    new webpack.DefinePlugin({
      'API_BASEURL': 'http://myapi.test'
    })
  );

  return config;
};
handhikadj commented 3 years ago

I don't want to declare environment variables in the config-override file, .env is the appropriate place to do this. any better way to do this?

dawnmist commented 3 years ago

All variables defined in your .env file(s) are available to you to use inside the config-overrides.js file (react-scripts will have already initialized the environment using those files by the time that config-overrides is run). What react-scripts does is only pass to the finished application those that start with REACT_APP, but by using the DefinePlugin yourself in config-overrides you should be able to pass any additional ones you want through manually.

const webpack = require('webpack');

module.exports = (config) => {
  ...
  config.plugins.push(
    new webpack.DefinePlugin({
      'API_BASEURL': process.env.API_BASEURL
    })
  );

  return config;
};
handhikadj commented 3 years ago

I can do it in the cleaner way: config.plugins.push(new webpack.DefinePlugin(process.env));