Output an ES module using webpack

前端 未结 4 515
不思量自难忘°
不思量自难忘° 2020-12-05 03:38

With Rollup I can output an ES module by simply setting the format option to \'es\'. How can I do the same with webpack? If it\'s not possible now,

4条回答
  •  醉酒成梦
    2020-12-05 04:15

    If you don't mind adding an additional file to your package , you can use this workaround as a solution that allows you to distribute/import Webpack bundles as ES6 modules:

    Configuration

    webpack.config.js

    output: {
        path: path.resolve('./dist'),
        filename: 'bundle.js',
        library: '__MODULE_DEFAULT_EXPORT__',
        libraryTarget: 'window',
        libraryExport: 'default'
      },
    

    ./dist/index.js (we need to create this file)

    import './bundle.js'
    const __MODULE_DEFAULT_EXPORT__ = window.__MODULE_DEFAULT_EXPORT__
    delete window.__MODULE_DEFAULT_EXPORT__
    export default __MODULE_DEFAULT_EXPORT__
    

    package.json (important if you are going to distribute your module)

      "main": "dist/index.js",
    

    How it works :

    • Webpack outputs the bundle to /dist/bundle.js, using the window as libraryTarget method. According to my configuration, this makes the package default export available as window.__MODULE_DEFAULT_EXPORT__, as soon as it's imported.
    • We create a custom "loader" : ./dist/index.js, which imports the /dist/bundle.js , picks the window.__MODULE_DEFAULT_EXPORT__ , deletes it from the window object (cleanup), assigns it to a local variable, and exports it as a ES6 export.
    • We configure our package.json to point to our "loader" : ./dist/index.js
    • We can now perform a regular import MyDefaultExportName from './dist/index.js'

    Note : This solution -as it is exposed here- is far from being perfect, and has some downsides and limitations. Although there is space for improvements :)

提交回复
热议问题