ES模块从另一个模块导入一个单一值是否值得?

huangapple go评论96阅读模式
英文:

Is ES module import from another module worthwhile for a single value?

问题

我理解 ES 模块在下面的示例中只加载一次。在仅需要一个或少数几个简单变量时,最好的方法是什么?

mod1.js

export class One {

  static android = navigator.userAgent.includes('Android');
  // --- 更多代码
}

mod2.js

import {One} from './mod1.js';

export class Two {
  
  // 仅需要 One.android
  // --- 更多代码
}

background.js

import {One} from './mod1.js';
import {Two} from './mod2.js';

// --- 更多代码

由于 background.js 导入了两个模块,且模块仅加载一次,是否值得将 mod1.js 仅为一个变量导入到 mod2.js?还是重新定义变量会更好?例如:

mod2.js

export class Two {
  
  static android = navigator.userAgent.includes('Android');
  // --- 更多代码
}
英文:

I understand that ES modules are loaded only once in the following example. What is the best approach when only one, or a few, simple variables are needed?

mod1.js

export class One {

  static android = navigator.userAgent.includes('Android');
  // --- more code
}

mod2.js

import {One} from './mod1.js';

export class Two {
  
  // needs only One.android
  // --- more code
}

background.js

import {One} from './mod1.js';
import {Two} from './mod2.js';

// --- more code

Since background.js imports both modules, and modules are loaded only once, is it worthwhile to import mod1.js into mod2.js only for one variables? Or would it better to redefine the variable? e.g.

mod2.js

export class Two {
  
  static android = navigator.userAgent.includes('Android');
  // --- more code
}

答案1

得分: 1

坚持导入您的模块,因为这样更干净,也尊重DRY原则。愉快编码!

英文:

Just stick with importing your modules since it's cleaner and respects the DRY principle. Happy coding!

huangapple
  • 本文由 发表于 2023年4月20日 01:20:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76057245.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定