Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Require Webpack bundle -- returns empty object?

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


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

In a node server.js I have var foo = require("./foo.js")

When I console.log(foo) I get an empty object {}

What am I doing wrong??

My webpack config:

module.exports = {
    entry: "./test.js",
    output: {
        filename: "./foo.js"
    },
    target: "node",
    module: {
        loaders: [
            {
                exclude: /(node_modules|bower_components)/,
                loader: "babel?presets[]=react,presets[]=es2015"
            }
        ]
    },
    devtool: "#source-map"
};
like image 695
neaumusic Avatar asked Jul 10 '16 05:07

neaumusic


2 Answers

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

like image 116
TN1ck Avatar answered Oct 23 '22 02:10

TN1ck


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.

like image 41
mbraint Avatar answered Oct 23 '22 03:10

mbraint