首页 > 解决方案 > 使用 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.jsmaster_entry -webpack-> main.js

即,webpack 首先运行file_1.js,然后在导入file_1包和file_2.js.

标签: javascriptwebpackbabeljsnode-moduleses6-modules

解决方案


我想我有一个解决方案;)

// 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>

您现在还可以将选项传递给函数。看看我的解决方案


推荐阅读