Javascript 在 ES6 中导出多个变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34645731/
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
Export more than one variable in ES6?
提问by alexchenco
I'm trying to export more than one variable in ES6:
我试图在 ES6 中导出多个变量:
exports.js
导出.js
var TestObject = Parse.Object.extend('TestObject')
var Post = Parse.Object.extend('Post')
export default TestObject
export Post
main.js:
主要.js:
import TestObject from '../store'
import Post from '../store'
var testObject = new TestObject() // use Post in the same way
testObject.save(json).then(object => {
console.log('yay! it worked', object)
})
I understand that there's only one default value so I only used default
in the first item.
我知道只有一个默认值,所以我只default
在第一项中使用。
However, I get this error message:
但是,我收到此错误消息:
Module build failed: SyntaxError: /home/alex/node/my-project/src/store/index.js: Unexpected token (9:7)
7 |
8 | export default TestObject
> 9 | export Post
Maybe I'm doing it the wrong way?
也许我做错了?
回答by loganfsmyth
That is not valid syntax. You can do
那不是有效的语法。你可以做
export {Post}
or even just
甚至只是
export var Post = Parse.Object.extend('Post')
or shorten the whole file to
或将整个文件缩短为
export default Parse.Object.extend('TestObject')
export var Post = Parse.Object.extend('Post')
Your imports are also incorrect, you'll want to do
你的进口也不正确,你会想要做
import TestObject, {Post} from '../store'
This is if you really want a single default export and a separate named export. You can also just make two named exports and have no default if you want, e.g.
这是如果您真的想要一个默认导出和一个单独的命名导出。如果需要,您也可以只进行两个命名导出并且没有默认值,例如
export var TestObject = Parse.Object.extend('TestObject'),
Post = Parse.Object.extend('Post')
and
和
import {TestObject, Post} from '../store'
回答by Mario Tacke
You can export multiple objects like this in ES6
你可以在 ES6 中像这样导出多个对象
var TestObject = Parse.Object.extend('TestObject')
var Post = Parse.Object.extend('Post')
export {
TestObject,
Post
}
Then, when importing you do it like this:
然后,在导入时,您可以这样做:
import { TestObject, Post } from './your-file';
回答by Pablo Rocha
If it fits your use case you can make the non-default export a property of your default export. I find it makes for cleaner code.
如果它适合您的用例,您可以将非默认导出设为默认导出的属性。我发现它使代码更清晰。
const TestObject = Parse.Object.extend('TestObject');
TestObject.Post = Parse.Object.extend('Post');
export default TestObject;
Then, when importing you only need to import the default:
然后,在导入时您只需要导入默认值:
import TestObject from './your-file.js';
Then, you use it like so:
然后,您可以像这样使用它:
TestObject.Post({some, args});