ember.js 如何从ember-cli-build.js访问环境参数

mpbci0fu  于 2022-11-05  发布在  其他
关注(0)|答案(4)|浏览(124)

当您执行以下操作时:

ember build --environment="production"

environment参数在config/environment.js中可用:

module.exports = function(environment) {
  ...
};

我还需要从ember-cli-build.js中访问环境:

let STATIC_URL = "TODO";  // This depends on the deploy "environment" parameter

module.exports = function(defaults) {
  let app = new EmberApp(defaults, {
    fingerprint: {
      enabled: true,
      prepend: STATIC_URL,
    },
  });

  return app.toTree();
};

如何从ember-cli-build.js访问环境参数?

62lalag4

62lalag41#

编辑

我只是意识到你需要的环境已经在ember-cli-build.js中,而不仅仅是在app.js中,所以这个答案可能不起作用。
我的配置有点不同,但环境的包含是相同的:

// app.js - I stripped some unrelated stuff
import Ember from 'ember';
import Resolver from 'ember/resolver';

import ENV from 'my-appname/config/environment';

var App;

App = Ember.Application.extend({
  fingerprint: {
     enabled: true,
     prepend: ENV.STATIC_URL,
  },
  modulePrefix: config.modulePrefix,
  podModulePrefix: config.podModulePrefix,
  Resolver: Resolver,
});

export default App;

现在,您可以根据传递到的环境更改enviroment.js中的STATIC_URL:

// config/enviroment.js
module.exports = function(environment) {
    var ENV;
    if(environment==='production') {
        ENV.STATIC_URL='foo';
    }
    return ENV;
}

请注意,config/environment位于您的 dasherized 应用程序名称下。

tuwxkamq

tuwxkamq2#

ember-cli-build.js中,您可以调用EmberApp.env(),如下所示:

let STATIC_URL = EmberApp.env() === 'development' ? "TODO" : "READY";

module.exports = function(defaults) {
  let app = new EmberApp(defaults, {
    fingerprint: {
      enabled: true,
      prepend: STATIC_URL,
    },
  });

  return app.toTree();
};
ef1yzkbh

ef1yzkbh3#

在我们的Brocfile.js(我猜你的名字叫ember-cli-build.js?)中,我们正在做类似这样的事情:

var EmberApp = require('ember-cli/broccoli/ember-app');
var environment = process.env.EMBER_ENV || 'development';
var config = require('./config/environment')(environment);

var app = new EmberApp(/* configuration for the app... */ );
module.exports = app.toTree();

在我们给环境变量赋值的那一行,你可以得到你所处的环境。我们使用了EMBER_ENV命令行变量,但你也可以使用其他的变量。基本上在我们所有的代码中,我们都是这样运行ember的:

EMBER_ENV=production ember-cli start
EMBER_ENV=test ember-cli test

# the next lines use the same 'development' environment

EMBER_ENV=development ember-cli start
ember-cli start
siotufzp

siotufzp4#

我使用的是Ember 2.5。要访问ember-cli-build.js中的环境参数,请使用process.env.EMBER_ENV。下面是我的ember-cli-build.js:

let EmberApp = require('ember-cli/lib/broccoli/ember-app');

module.exports = function(defaults) {
  let app = getApp(defaults, process.env.EMBER_ENV);

  // Use `app.import` to add additional libraries to the generated
  // output files.

  return app.toTree();
};

function getApp(defaults, environment) {
  switch(environment) {

    case "production":
      return new EmberApp(defaults, {
        fingerprint: {
          enabled: true
        },
      });

    default:
      return new EmberApp(defaults, {
        fingerprint: {
          enabled: false
        },
      });     

  }
}

相关问题