Javascript 在 ES6 中导出常量的正确方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43937561/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the correct way to export a constant in ES6?
提问by jhodgson4
I'm trying to break my entry file into components but I'm not sure how to make the constant available to the import. This is what I've tried so far and both seem to work:
我试图将我的入口文件分解为组件,但我不确定如何使常量可用于导入。这是我迄今为止尝试过的方法,两者似乎都有效:
export const ConnectedRange = connectRange(Range);
exports.ConnectedRange = connectRange(Range);
I've seen the latter used in some npm packages but sure what to use?
我见过后者在一些 npm 包中使用,但确定使用什么?
Thanks
谢谢
采纳答案by Alex Faunt
export const ConnectedRange = connectRange(Range);
出口 const ConnectedRange = connectRange(Range);
Is the ES modules syntax.
是 ES 模块语法。
exports.ConnectedRange = connectRange(Range);
export.ConnectedRange = connectRange(Range);
Is the commonJS syntax.
是 commonJS 语法。
I would recommend using the ES modules syntax, and compiling to common JS if the environment you run your code on does not support ES modules.
如果您运行代码的环境不支持 ES 模块,我会建议使用 ES 模块语法,并编译为通用 JS。
回答by Ematipico
As you pointed ES6 modules
正如你指出的 ES6 模块
export const CONNECT_RANGE = connectRange(Range);
And when you want to consume it
当你想消费它时
import { CONNECT_RANGE } from './myModule';
回答by novonimo
With considering all the above answers, you can also export your constant as well as a module in ES6:
考虑到上述所有答案,您还可以在 ES6 中导出常量和模块:
module.exports = yourConstant;
and call it from your file:
并从您的文件中调用它:
import yourConstant(JavaScript)
导入 yourConstant( JavaScript)
require yourConstant(Node JS)
需要 yourConstant( Node JS)

