Node.js 使用导出而不是module.exports的汇总捆绑包
我有一个使用rollup绑定的库,这是Node.js 使用导出而不是module.exports的汇总捆绑包,node.js,rollupjs,Node.js,Rollupjs,我有一个使用rollup绑定的库,这是rollup.config.js文件中的一部分: export default { input: `src/${libraryName}.ts`, output: [ { file: pkg.main, name: camelCase(libraryName), format: 'cjs', sourcemap: true }, { file: pkg.module, format: 'es', sourcemap: true },
rollup.config.js
文件中的一部分:
export default {
input: `src/${libraryName}.ts`,
output: [
{ file: pkg.main, name: camelCase(libraryName), format: 'cjs', sourcemap: true },
{ file: pkg.module, format: 'es', sourcemap: true },
],
....
}
它生成两个文件dist/libname.umd.js
和dist/libname.es5.js
。在使用require('libname')
加载dist/libname.umd.js
的两个文件中放置console.log
语句,我已经确认了这一点。但是,以下行:
var x = require('libname').X
console.log(x) // This is undefined
打印未定义的
。因此,我尝试手动编辑dist/libname.umd.js
文件,并在文件底部看到:
exports.X = X;
将整个变量X
捆绑在文件上方的某个位置。我将其修改为:
module.exports.X = X;
然后它似乎起作用了。我对node/js有点陌生,所以我不确定这是否是导出模块的方法,但在阅读一篇博客文章()时,发现这两种方法都可以吗?不过我还是有点不清楚
还有,当我这么做的时候:
console.log(require('libname')
它打印[函数:uniqSetWithForEach]
和控制台.log(require('libname')())
打印[]
编辑目前,为了继续我的工作,我修改了rollup.config.ts
以添加一个outro
:
export default {
...
output: [
{ file: pkg.main, name: camelCase(libraryName), format: 'cjs',
sourcemap: true,
outro: 'module.exports = Object.assign({}, module.exports, exports)'
}
]
...
}
现在看来这是可行的,但我很确定这不是一个干净的解决方案。值得一提的是,它不适用于默认导出(您可能会编写
module.exports=MyComponent
)。真的救了我当前的一个项目。谢谢你的解决方案!