no window object present webpack nodejs

匿名 (未验证) 提交于 2019-12-03 00:59:01

问题:

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'); 

回答1:

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

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


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!