javascript - 使用 webpack output.target 选项创建 ES6 模块“等效”
问题描述
首先,道歉!我努力总结标题中的问题,所以请随时修改。
问题
假设我有两个暴露默认函数的 ES6 文件
// file_1.js
export default function(){ /* do the thing */ }
// file_2.js
export default function(){ /* do the other thing */ }
现在我file_1
使用以下输出配置使用 webpack(w/ babel loader)捆绑到一个模块中
// 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
?
我尝试过使用 webpackoutput
选项,例如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
.
解决方案
我想我有一个解决方案;)
// 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>
您现在还可以将选项传递给函数。看看我的解决方案
推荐阅读
- javascript - IOS 找不到变量:ImageCapture
- php - 如何在functions.php中创建301重定向规则
- image - Symfony通过文章内部的表单获取图像
- date - 添加新行时自动插入日期戳
- c++ - 使用 ucnv_convert() 时为韩语显示垃圾字符
- twitter - Twitter API - 为拥有数百万关注者的帐户获取关注者列表的有效方法
- vhdl - 'high/'low 的函数重载
- python - Python DataFrame 只有一列
- spring - JPA 允许字符串作为主键
- typescript - 我想在 Vue 中显示多个组件