ES6导出模板生成器

时间:2019-05-08 11:00:53

标签: javascript ecmascript-6 es6-modules

使用CommonJS,我可以执行以下操作:

generator.js

module.exports = (...args) => ({
  create: makeCreate(...args),
  remove: makeRemove(...args),
});

model.js

const generate = require('generator.js');

module.exports = generate('my-model');

use.js

const { create, remove } = require('model.js');

module.exports = {
  doCreate: () => create('something'),
  doRemove: () => remove('something else'),
};

使用ES6模块,我可以重构为以下内容:

generator.mjs

export default (...args) => ({
  create: makeCreate(...args),
  remove: makeRemove(...args),
});

model.mjs

import generate from 'generator.mjs';

export default generate('my-model');

use.mjs

import model from 'model.mjs';

export const doCreate = () => model.create('something');
export const doRemove = () => model.remove('something else');

但是,model.mjs本身的导出方式意味着我 无法做到这一点:

use.mjs

import { create, remove } from 'model.mjs';

export const doCreate = () => create('something');
export const doRemove = () => remove('something else');

我想不出一种在generator.mjsmodel.mjs中简洁定义导出的方法,以实现上述目的。可以吗?

1 个答案:

答案 0 :(得分:0)

替代品:

您可以在use.mjs

中执行类似的操作
import model from 'model.mjs';

const {create, remove} = model;

export const doCreate = () => create('something');
export const doRemove = () => remove('something else');

另一个解决方案是:

model.mjs

import generate from "./generator.js";

export const { create, remove } = generate("my-model");

use.mjs

import { create, remove } from "./model.js";

export const doCreate = () => create("something");
export const doRemove = () => remove("something else");