[英]Export a class after definition in ES6
// test.js
class Test
export Test
// index.js
import {Test} from './test'
This results in a syntax error with Unexpected token
. 这会导致Unexpected token
出现语法错误。 What is the correct way to export a predefined class? 导出预定义类的正确方法是什么?
EDIT: It is required that the class definition is separate from the export. 编辑:要求类定义与导出分开。
To elaborate 详细说明
export {A, B};
Is the same as 是相同的
// old style
exports.A = A;
exports.B = B;
Which require an import
like 这需要像import
一样
import {A,B} from "./somefile";
Which is the same as 哪个是一样的
// old style
var A = require("./somefile").A;
var B = require("./somefile").B;
However, you also could've also used export default
但是,您也可以使用export default
class Test {
constructor() {
console.log("it's works");
}
}
export default Test;
Which is the same as 哪个是一样的
// old style
exports["default"] = Test;
module.exports = exports["default"];
Then import it like 然后导入它就像
import Test from "./test";
new Test();
// "it works!";
Which is the same as 哪个是一样的
// old style
var Test = require("./test");
new Test();
// "it works!";
正确的方法是使用export {Test}
。
You just need to change your test.js: 你只需要改变你的test.js:
export class Test
Then 然后
import {Test} from './test'
You can both do 你们俩都可以
class MyClass { }
export { MyClass }
or 要么
export default MyClass // no semicolon
And then 接着
import { MyClass as Stuff } from './modulepath';
or (if you declare export default) 或(如果您声明导出默认值)
import { default as MyClass } from './modulepath';
or simply 或者干脆
import MyClass from './modulepath';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.