True ENV Values in Laravel Mix

后端 未结 3 1399
面向向阳花
面向向阳花 2021-02-15 18:33

So in Laravel Mix it says in the docs we can add stuff to our .env file prefixed with MIX_ and we can then access it in our JS file when compiled.

I think I may be missi

相关标签:
3条回答
  • 2021-02-15 18:53

    @Ohgodwhy's answer works, but need slight modification for new mix version

    require('dotenv').config()
    let webpack = require('webpack')
    
    let dotenvplugin = new webpack.DefinePlugin({
        'process.env': {
            APP_NAME: JSON.stringify(process.env.APP_NAME || 'Default app name'),
            NODE_ENV: JSON.stringify(process.env.NODE_ENV || 'development')
        }
    })
    
    mix.webpackConfig({
        ...
        plugins: [
            dotenvplugin,
        ]
    
    0 讨论(0)
  • 2021-02-15 19:01

    Here is the way I ended up doing this:

    Anyone landing here from google here is how I did this:

    env.js

    let globalEnv = {
      development: {
        embedScriptUrl: 'http://localjspath.js',
        embedCssUrl: 'http://localcsspath.css',
      },
     production: {
        embedScriptUrl: 'https://s3.us-east-2.amazonaws.com/pathtojs.js',
        embedCssUrl: 'https://s3.us-east-2.amazonaws.com/pathtocss.css',
      }
    };
    
    export default function env(property){
      return globalEnv[process.env.NODE_ENV][property];
    };
    

    You then just import and call env('embedScriptUrl') in your front end JS like you would in a laravel PHP file

    0 讨论(0)
  • 2021-02-15 19:03

    You can do it like this:

    Setup steps:

    1. npm install dotenv --save
    2. Add require('dotenv').config() at the top of your webpack.mix.js file
    3. add let webpack = require('webpack') after #2

    Now you can inject these into your build by using the DefinePlugin in your mix declaration:

    mix.webpackConfig({
      //...
      new webpack.DefinePlugin({
        'process.env': {
          APP_NAME: JSON.stringify(process.env.APP_NAME || 'Default app name'),
          NODE_ENV: JSON.stringify(process.env.NODE_ENV || 'development')
        }
      })
    })
    

    Now your bundled files can use process.env.APP_NAME, for instance, in the application. This safe guards you from exposing your .env file to the browser but allows you to easily share global, insecure values through the full stack.

    Notes

    Note that the process.env does not get replaced with the .env from Laravel, but rather it exposes it through a merge. Therefore if you are passing, for instance, arguments to npm/yarn run dev (such as NODE_ENV=development), then you do not need to declare NODE_ENV in your .env file. If you do, the .env file will take presedence.

    0 讨论(0)
提交回复
热议问题