Fullstack accessing simple string from node, webpack and react

35 Views Asked by At

I thought this would be a simple taks, but it's proving impossible.

I got this project structure

project-root/
├── .env
├── config/
├── node/
├── server.js
└── app/
    ├── src/
    │   └── home.tsx
    └── webpack/
        └── options.js

Basically all I want is to have a simple string to be accessible by server.js, home.tsx and options.js this last one is a file that's part of the webpack setup.

I have tried dotenv and config but webpack is not having it.

Any ideas?

Note:

I need this string to load as part of the proxy config in the dev webpack configuration so loading it as a plugin will fail as I need this string ready before that.

The server.js accessing the variable

import 'dotenv/config'
...
app.use(`/${process.env.APP_API}`, router)

router.get('/main', (req, res) => {
  res.send('Hello')
})

The webpack dev config

...
devServer: {
  publicPath: '/',
  open: true,
  https: false,
  port: localPort,
  proxy: {
    [`/${process.env.APP_API}`]: {
      target: `http://localhost:${apiPort}`,
      secure: false
    }
 },
...

The react Home.tsx file accessing the string

const connectBackEnd = async () => {
  try {
    const { data } = await axios(`/${process.env.APP_API}/main`)
    setText(data)
  } catch (error) {
    console.log(error)
  }
}
1

There are 1 best solutions below

3
Álvaro On

I figured it out.

I did this from options.js on webpack

import { resolve } from 'path'
import { config } from 'dotenv'

const envPath = resolve(__dirname, '../../.env')

config({ path: envPath })

console.log(process.env.APP_API)