没有窗口对象存在webpack nodejs

时间:2016-02-29 16:47:24

标签: javascript node.js webpack

我正在使用带有babel的webpack来编译我的ecmascript 6代码。一切正常,但如果我添加某些dependeciens喜欢请求npm包。这是我的文件:

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']
  }
}

现在,如果我运行webpack然后运行node dist/stella.js一切正常,请注销registering...;但是,如果我添加某些依赖项,如requests npm包:

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

我运行webpack所有内容都会编译而没有错误,但我尝试运行node dist/stella.js并收到此错误:

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

1 个答案:

答案 0 :(得分:11)

默认情况下,Webpack设置为以浏览器为目标,而不是Node环境。尝试在配置中设置target

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