Require Webpack - returns an empty object?

Update module.exports = : How to add module.exports = to webpack?


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

In 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 configuration:

 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" }; 
+9
source share
2 answers

I think you are missing libraryTarget -setting. Adding libraryTarget: "commonjs2" to the configuration should fix the problem. See this in webpack-docs .

+12
source

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

 "libraryTarget": "commonjs2" 

I have the 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 to:

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

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

UPDATE:

Webpack authors do not recommend using babel-plugin for this.

Webpack 3 has an output.libraryExport option (you don’t have any detailed documents right now)

I tried like this

 output.libraryExport: 'default' 

and this fixed the problem.

+6
source

All Articles