Laravel Mix中的真实ENV值 [英] True ENV Values in Laravel Mix

查看:272
本文介绍了Laravel Mix中的真实ENV值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此在Laravel Mix中,它说在文档中我们可以将内容添加到以MIX_为前缀的.env文件中,然后在编译时可以在JS文件中对其进行访问.

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.

我想我可能会在这里丢失一些东西,因为这实际上并没有提供任何env文件的内容,因为在将资产推送到服务器之前,这些资产已在本地编译为生产模式.那意味着npm run watch和npm run build都会选择相同的env值吗?

I think I may be missing something here though because this doesn't really offer anything along the lines of an env file as the assets are compiled into production mode locally before you push them up to your server. That means the npm run watch and npm run build will both pick up the same env values right?

它可以用作全局变量,但不能用作环境变量,因为您不能根据环境的不同来设置值,

It works as a kind of global variable thing but not as an environment variable as you can't set the value depending on what the environment is,

这似乎很明显,所以我认为我错过了什么?

This seems kind of obvious so I assume I missing something ??

推荐答案

您可以这样做:

设置步骤:

  1. npm install dotenv --save
  2. webpack.mix.js文件顶部添加require('dotenv').config()
  3. 在#2之后添加let webpack = require('webpack')
  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

现在,您可以使用mix声明中的DefinePlugin将它们注入到您的构建中:

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')
    }
  })
})

例如,现在您的bundled文件可以在应用程序中使用process.env.APP_NAME.这样可以防止您将.env文件暴露给浏览器,但可以让您轻松地通过整个堆栈共享全局的,不安全的值.

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.

注释

请注意,process.env不会被Laravel的.env取代,而是通过合并公开它.因此,例如,如果您要传递npm/yarn run dev的参数(例如NODE_ENV=development),则无需在.env文件中声明NODE_ENV.如果这样做,.env文件将具有优先权.

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.

这篇关于Laravel Mix中的真实ENV值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆