使用混合命名和默认导出从 ESM 构建 CJS 模块 - 如何省略“默认”?

问题描述 投票:0回答:2

我正在尝试配置 rollup 以从现有 esm 构建 commonjs 模块。 我有一组单独的独立方法,使用

default
导出,并且可以直接从包中导入,例如:

import method1 from 'lib/method1'

而且我对所有这些都有一个入口点

standalone.js
,让用户代码使用解构单独导入它们或立即作为 lib 导入它们。

import _method1 from './method1'
import _method2 from './method2'
import _method3 from './method3'

export const method1 = _method1;
export const method2 = _method2;
export const method3 = _method3;

export default {method1,method2,method3};

这是用法示例:

import method1 from 'lib/method1'
//or
import { method1 } from 'lib/standalone'
//or
import standalone from 'lib/standalone'
//standalone.method1();

所有这些对于 esm 来说都很好,我希望对于 cjs 来说有类似的经验。 汇总所做的一切几乎都是正确的,但它抱怨混合命名/默认导出并添加额外的

module.exports.default
字段:

'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var condense$1 = require('./condense.js');
var condenseDeep$1 = require('./condenseDeep.js');
var eachDeep$1 = require('./eachDeep.js');
// ...


var condense = condense$1;
var condenseDeep = condenseDeep$1;
var eachDeep = eachDeep$1;
//...

var standalone = {
  condense: condense$1,
  condenseDeep: condenseDeep$1,
  eachDeep: eachDeep$1,
  //...
};

exports.condense = condense;
exports.condenseDeep = condenseDeep;
exports.default = standalone; // <-- this one, how to remove it?
exports.eachDeep = eachDeep;
//...

所以在 commionjs 中的用法如下:

const method1 = require('lib/method1');
//or
const { method1 } = require ('lib/standalone');
//or
const standalone = require('lib/standalone');
//standalone.method1();
//standalone.default <--- this is redundant and confusing

我尝试了

output.exports: 'named'
汇总选项 - 仅使用默认值的其他入口点也开始具有
module.exports.default = ..
而不是预期的
module.exports = ..

我尝试了

output.exports: 'default'
- 它不适用于混合默认/命名导出,引发错误。

javascript commonjs rollup es6-modules
2个回答
2
投票

A

default
导出 is 一个命名导出,它只是命名为
default
。 ESM 的构建方式是,如果您不指定名称,它将使用 JS 文件中名为
default
的导出。

使用CJS,没有

default
导出的概念,一切都是命名的。

重点是,这里没有任何问题。您不能混合命名导出和默认导出并使用它们而不在 CJS 中指定

.default

也许这个要点会帮助你。

编辑:你总是可以破解它正如这个答案所暗示的,但它是一个黑客,然后你会失去

named
出口。


0
投票

我们可以通过修补汇总来实现这一点。

https://github.com/avisek/rollup-patch-seamless-default-export

// Default export
const lib = require('your-library')
lib('Hello') // <-- instead of using `.default` property

// Named exports
const { namedExport1, namedExport2 } = lib

// One liner syntex. Also supported.
const { default: defaultExport, namedExport1, namedExport2 } = require('your-library')
© www.soinside.com 2019 - 2024. All rights reserved.