首先,道歉!我在标题中艰难地总结了这个问题,所以请随时修改。
问题所在
假设我有两个公开默认函数的ES6文件
// file_1.js
export default function(){ /* do the thing */ }
// file_2.js
export default function(){ /* do the other thing */ }现在,我使用webpack (w/ babel loader)将file_1捆绑到一个模块中,输出配置如下
// webpack config 1.
{
...
entry : '/path/to/file_1.js'
output : {
path: '/where/it/goes/',
filename : 'main.js',
library: 'my_component',
libraryTarget: 'var'
}
}我还有一个最小的package.json,所以它可以作为npm模块{ name: 'file_1', main: 'main.js' }导入。
现在,当我想以一种统一的方式将来自file_1和模块file_2的代码捆绑在一起时,挑战来了。
// master_entry.js
const components = {
file_1 : require('file_1'),
file_2 : require('/path/to/file_2')
}如果我将以上代码捆绑在一起,并查看components的结果形式,它看起来如下所示
console.log(components.file_1)
// outputs
Module {__esModule: true, Symbol(Symbol.toStringTag): "Module" }console.log(components.file_2)
// outputs
Module {default: f, __esModule: true, Symbol(Symbol.toStringTag): "Module" }因此,对于file_2 (没有预先捆绑),我有可用的默认函数--这就是我想要的。如何在捆绑file_1时实现相同的功能
我尝试过使用output选项,比如library,libraryTarget,libraryExport,等等。然而,我现在有点迷失了,并且已经在文档中花费了很长时间--因此我需要帮助!
提前谢谢。
为了清楚起见
file_1.js -webpack-> package file_1 (入口点file_1.js) master_entry -webpack-> main.js
也就是说,webpack首先在file_1.js上运行,然后在导入file_1包和file_2.js的组合上运行。
发布于 2019-05-28 05:46:03
我想我有一个解决方案;)
// file_1.js
export default function file1(){ console.log('file_1') }
// file_2.js
export default function file2(){ console.log('file_2') }webpack.config.js应该如下所示
entry: {
file1: './sources/js/file_1.js',
file2: './sources/js/file_2.js',
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: './[name].js',
library: '[name]',
libraryExport: 'default',
libraryTarget: 'umd', // you can use libraries everywhere, e.g requirejs, node
umdNamedDefine: true,
},从现在开始,您可以访问:
<script>
new file1(); // console.log show file_2
new file2(); // console.log show file_2
</script>现在还可以将选项传递给函数。看看我的solution
https://stackoverflow.com/questions/56270596
复制相似问题