使用 webpack output.target 选项创建 ES6 模块“等效”
Posted
技术标签:
【中文标题】使用 webpack output.target 选项创建 ES6 模块“等效”【英文标题】:Create ES6 module 'equivalent' using webpack output.target options 【发布时间】:2019-10-09 18:07:27 【问题描述】:首先,道歉!我很难在标题中总结问题,所以请随时修改。
问题
假设我有两个公开默认函数的 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
时如何实现相同的效果?
我尝试过使用 webpack output
选项,例如 library
、libraryTarget
、libraryExport
。但是我有点迷茫,现在在文档中花了很长时间 - 因此呼救!
提前致谢。
为清楚起见
file_1.js
-webpack->
包file_1
(入口点file_1.js
)
master_entry
-webpack->
main.js
也就是说,webpack 首先在 file_1.js
上运行,然后在导入 file_1
包和 file_2.js
的组合上运行。
【问题讨论】:
您能给我们提供一个存储库的链接吗?另外,我不确定您为什么将条目指定为 file1 而不是 master_entry.js。 @StavAlfi 在上面添加了说明。 Webpack 运行了两次。首先生成一个包,然后捆绑一个使用该包的文件。 @StavAlfi 没有单一的存储库。如果我有能力改变所有的活动部件,我可以一次完成 webpack 而不会有任何问题。 【参考方案1】:我想我有一个解决方案;)
// 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
【讨论】:
@Grzegprz .T - 我无法对此进行测试,因为我们最终走了另一条路线。我投了赞成票,如果其他人登陆这里并确认它有效,我将很乐意接受答案。感谢发帖!以上是关于使用 webpack output.target 选项创建 ES6 模块“等效”的主要内容,如果未能解决你的问题,请参考以下文章