目前我正在做这个:
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对象中声明常量会让人感到尴尬。
当前回答
最后,我导出了一个带有匿名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
});
其他回答
我建议使用webpack(假设你正在使用webpack)。
定义常量就像设置webpack配置文件一样简单:
var webpack = require('webpack');
module.exports = {
plugins: [
new webpack.DefinePlugin({
'APP_ENV': '"dev"',
'process.env': {
'NODE_ENV': '"development"'
}
})
],
};
通过这种方式,您可以在源代码之外定义它们,并且它们将在您的所有文件中可用。
在我看来,使用Object.freeze可以实现dry和更声明性的风格。我喜欢的模式是:
/ lib / constants.js
module.exports = Object.freeze({
MY_CONSTANT: 'some value',
ANOTHER_CONSTANT: 'another value'
});
/ lib / some-module.js
var constants = require('./constants');
console.log(constants.MY_CONSTANT); // 'some value'
constants.MY_CONSTANT = 'some other value';
console.log(constants.MY_CONSTANT); // 'some value'
ES6路。
在foo.js中导出
const FOO = 'bar';
module.exports = {
FOO
}
导入到bar.js中
const {FOO} = require('foo');
您可以使用global显式地将其导出到全局作用域。Foo = 5。然后,您只需请求该文件,甚至不保存返回值。
但说真的,你不应该这么做。保持适当的封装是一件好事。你已经有了正确的想法,所以继续做你正在做的事情。
因为Node.js使用的是CommonJS模式,所以你只能在模块与模块之间共享变量。导出或者像在浏览器中那样设置全局变量,但你用的不是window而是global。Your_var = value;