Create ES6 module 'equivalent' using webpack output.target options

邮差的信 提交于 2019-12-10 21:06:07

问题


Firstly, apologies! I struggled summing up the issue in the title so please feel free to amend.

The problem

Suppose I have two ES6 files that expose default functions

// file_1.js
export default function(){ /* do the thing */ }

// file_2.js
export default function(){ /* do the other thing */ }

Now I bundle file_1 into a module using webpack (w/ babel loader) using the following output configuration

// webpack config 1.
{
   ...
   entry : '/path/to/file_1.js'
   output : {
      path: '/where/it/goes/',
      filename : 'main.js',
      library: 'my_component',
      libraryTarget: 'var'
   }
}

I also have a minimal package.json so it can be imported as a npm module { name: 'file_1', main: 'main.js' }

Now the challenge comes when I want to bundle together the code from file_1 and the module file_2 and a uniform manner.

// master_entry.js

const components = {
    file_1 : require('file_1'),
    file_2 : require('/path/to/file_2')
}

If I bundle the above and look at the resulting form of components it looks like so

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" }

Hence for file_2 (which was not prebundled) I have the default function available - which is what I want. How do I achieve the same thing when bundling file_1?

I have tried playing around with the webpack output options such as library, libraryTarget, libraryExport. However I am a bit lost and have spent far to long in the docs now - hence the cry for help!

Thanks in advance.

For clarity

file_1.js -webpack-> package file_1 (entry point file_1.js) master_entry -webpack-> main.js

I.e, webpack is running first on file_1.js and subsequently upon the combination of importing the file_1 package and file_2.js.


回答1:


I think I have a solution ;)

// file_1.js
export default function file1(){ console.log('file_1') }

// file_2.js
export default function file2(){ console.log('file_2') }

The webpack.config.js should look like this

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,
},

From now you have access to:

<script>
  new file1(); // console.log show file_2
  new file2(); // console.log show file_2
</script>

You can also now pass options to functions. Take a look at my solution



来源:https://stackoverflow.com/questions/56270596/create-es6-module-equivalent-using-webpack-output-target-options

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!