在 ES6 中定义后导出类

Export a class after definition in ES6

本文关键字:定义 ES6      更新时间:2023-09-26
// test.js
class Test
export Test

// index.js
import {Test} from './test'

这会导致 Unexpected token 的语法错误。导出预定义类的正确方法是什么?


编辑:要求类定义与导出分开。

正确的方法是使用 export {Test} .

详细说明

export {A, B};

// old style
exports.A = A;
exports.B = B;

这需要像这样的import

import {A,B} from "./somefile";

这与

// old style
var A = require("./somefile").A;
var B = require("./somefile").B;

但是,您也可以使用export default

class Test {
  constructor() {
    console.log("it's works");
  }
}
export default Test;

这与

// old style
exports["default"] = Test;
module.exports = exports["default"];

然后像导入一样

import Test from "./test";
new Test();
// "it works!";

这与

// old style
var Test = require("./test");
new Test();
// "it works!";

你们都可以

class MyClass { }
export { MyClass }

export default MyClass // no semicolon

然后

import { MyClass as Stuff } from './modulepath';

或(如果您声明导出默认值)

import { default as MyClass } from './modulepath';

或者干脆

import MyClass from './modulepath';

你只需要改变你的测试.js:

export class Test

然后

import {Test} from './test'