Require Webpack bundle — returns empty object?

前端 未结 3 799
星月不相逢
星月不相逢 2021-01-07 23:20

Update -- related: How to prepend module.exports = to webpack bundle?


I have webpack compile a simple module.exports = \"asdfasdf\" to foo.j

相关标签:
3条回答
  • 2021-01-07 23:56

    I had the same problem since for jest I need @babel plugins. I wrote the whole project with babel-6. Now I tried it again with the suggestion of @mbraint. And it worked! So for webpack output property you need something like below:

        output: {
            path: path.join(__dirname, 'dist'),
            filename: '<output-file-name>.js',
            libraryTarget: 'commonjs2',
            libraryExport: 'default',
            library: '<ProjectName>'
        },
    

    Use the naming cases as I show. Happy coding ✌

    0 讨论(0)
  • 2021-01-08 00:11

    I think you are missing the libraryTarget-setting. Adding libraryTarget: "commonjs2" to the config should fix the issue. See the webpack-docs about it.

    0 讨论(0)
  • 2021-01-08 00:19

    In my case I have same problem when using babel-loader with Babel 6. Even when I set

    "libraryTarget": "commonjs2"
    

    I have results:

    const foo = require('some-module');
    console.log(foo) // is {}
    
    const bar = require('some-module').default;
    console.log(bar) // is default export of 'some-module'
    

    If you want:

    const foo = require('some-module');
    console.log(foo) // is default export of 'some-module'
    

    You can use: babel-plugin-add-module-exports

    UPDATE:

    The authors of webpack do not recommend using the babel-plugin for this.

    Webpack 3 has option output.libraryExport (it is don`t have detailed docs now)

    I tried like this

    output.libraryExport: 'default'
    

    and it resovled the problem.

    0 讨论(0)
提交回复
热议问题