Export more than one variable in ES6?

2019-03-15 02:41发布

I'm trying to export more than one variable in ES6:

exports.js

var TestObject = Parse.Object.extend('TestObject')
var Post = Parse.Object.extend('Post')

export default TestObject
export Post

main.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.

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?

3条回答
Anthone
2楼-- · 2019-03-15 03:05

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});
查看更多
我只想做你的唯一
3楼-- · 2019-03-15 03:07

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'
查看更多
小情绪 Triste *
4楼-- · 2019-03-15 03:20

You can export multiple objects like this in 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';

You can read all about import and export here.

查看更多
登录 后发表回答