仅为副作用而导入的ES6模块的公认做法

Accepted practice for an ES6 module imported just for side-effects?

本文关键字:模块 ES6 副作用 导入      更新时间:2023-09-26

我喜欢保持代码的模块化,所以我把这种代码放在一个单独的文件(overrides/extra.js)中:

import Ember from 'ember';
Ember.RSVP.configure('onerror', function(error) {
    ....
});
export default null;

这只是配置Ember.RSVP的副作用,但不会导出任何有价值的内容。然后我会将其导入app.js:

import dummy from './overrides/extra';

这是公认的做法吗?

是的,如果您的模块不需要导出任何数据,则接受,但如果不需要,则无需从模块导出任何数据:

import Ember from 'ember';
Ember.RSVP.configure('onerror', function(error) {
    ....
});

app.js:

import './overrides/extra';

我通常导出一个初始化函数:

  • 调用代码更明确
  • 调用代码能够在成功(或失败)时执行操作

我不知道Ember和它的初始化,但下面是它的样子:

import Ember from 'ember';
export default function initialize(){
    return new Promise(function(ok, nok){
        try { // or any other kind of failure detection
            Ember.RSVP.configure('onerror', function(error) {
                ok();
            });
            ... you may do other initializations here
            ok();
        } catch (e) {
            nok(e);
        }
    });
}

在呼叫代码中

import initEmber from './yourFile.js';
initEmber()
.then(function(){
    ... here you know Ember is ready
})
.catch(function(){
    ... damn it!
});

请注意,如果Ember初始化是同步的,并且可能不会失败,@RGraham的答案可能更适合您。