目前我正在做这个:
foo.js
const FOO = 5;
module.exports = {
FOO: FOO
};
并在bar.js中使用它:
var foo = require('foo');
foo.FOO; // 5
还有更好的办法吗?在exports对象中声明常量会让人感到尴尬。
目前我正在做这个:
foo.js
const FOO = 5;
module.exports = {
FOO: FOO
};
并在bar.js中使用它:
var foo = require('foo');
foo.FOO; // 5
还有更好的办法吗?在exports对象中声明常量会让人感到尴尬。
当前回答
因为Node.js使用的是CommonJS模式,所以你只能在模块与模块之间共享变量。导出或者像在浏览器中那样设置全局变量,但你用的不是window而是global。Your_var = value;
其他回答
从之前的项目经验来看,这是一个很好的方法:
在constants.js中:
// constants.js
'use strict';
let constants = {
key1: "value1",
key2: "value2",
key3: {
subkey1: "subvalue1",
subkey2: "subvalue2"
}
};
module.exports =
Object.freeze(constants); // freeze prevents changes by users
在main.js(或app.js等)中,使用如下:
// main.js
let constants = require('./constants');
console.log(constants.key1);
console.dir(constants.key3);
最后,我导出了一个带有匿名getter函数的冻结对象,而不是导出常量本身。这降低了由于简单的const名称输入错误而引入的严重错误的风险,因为在输入错误的情况下将抛出运行时错误。下面是一个完整的例子,它也使用ES6符号作为常量,确保唯一性,以及ES6箭头函数。如果在这种方法中有任何问题,将感激反馈。
'use strict';
const DIRECTORY = Symbol('the directory of all sheets');
const SHEET = Symbol('an individual sheet');
const COMPOSER = Symbol('the sheet composer');
module.exports = Object.freeze({
getDirectory: () => DIRECTORY,
getSheet: () => SHEET,
getComposer: () => COMPOSER
});
导入和导出(2018年可能需要像Babel这样的东西才能使用导入)
types.js
export const BLUE = 'BLUE'
export const RED = 'RED'
myApp.js
import * as types from './types.js'
const MyApp = () => {
let colour = types.RED
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import
我不认为从模块中入侵GLOBAL空间是一个好的实践,但在某些情况下,可能严格需要实现它:
Object.defineProperty(global,'MYCONSTANT',{value:'foo',writable:false,configurable:false});
必须考虑到这种资源的影响。如果没有正确命名这些常量,重写已经定义的全局变量的风险是真实存在的。
因为Node.js使用的是CommonJS模式,所以你只能在模块与模块之间共享变量。导出或者像在浏览器中那样设置全局变量,但你用的不是window而是global。Your_var = value;