Rodrigo Rodrigo - 13 days ago 6
Javascript Question

no window object present webpack nodejs

I'm using webpack with babel to compile my ecmascript 6 code. Everything works fine but if I add certain dependeciens like the requests npm package. Here are my files:

main.js

import os from 'os'

export class User {

constructor(username) {
this.username = username;
}

register() {
console.log("registering...");
}
}

var client = new User("hey")


console.log(user.register());


webpack config:

var webpack = require('webpack')

module.exports = {
entry: [
'./src/main.js'
],
output: {
path: "dist",
publicPath: "/dist/",
filename: "stela.js"
},
watch: false,
module: {
loaders: [{
test: /\.js$/,
// excluding some local linked packages.
// for normal use cases only node_modules is needed.
exclude: /node_modules/,
loader: 'babel'
}, {
test: /\.json$/,
loader: 'json-loader'
}]
},
externals: {
fs: '{}',
tls: '{}',
net: '{}',
console: '{}'
},
babel: {
presets: ['es2015'],
plugins: ['transform-runtime']
},
resolve: {
modulesDirectories: ['node_modules']
}
}


Now if I run
webpack
and then run
node dist/stella.js
everything works fine it logs out
registering...
; however, if I add certain dependencies like the
requests
npm package:

...
import request from 'request'
...


I run
webpack
everything compiles down with no errors but then I try running
node dist/stella.js
and I get this error:

throw new Error('no window object present');

Answer

By default, Webpack is set up to target the browser, not a Node environment. Try setting target in your config:

module.exports = {
    // ...
    target: "node",
    // ...
}
Comments