首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ReferenceError:使用webpack时未定义窗口

ReferenceError:使用webpack时未定义窗口
EN

Stack Overflow用户
提问于 2019-11-02 02:59:26
回答 1查看 1.7K关注 0票数 1

当我使用webpack编译我的项目时,我得到了一个window not defined错误,我似乎不能理解为什么。我尝试添加不同的加载器,并将全局对象设置为this,但似乎仍然无法使其正常工作。

错误

代码语言:javascript
复制
[nodemon] starting `node build/bundle.js`
^[[A/Users/schachte/Desktop/node_modules/golden-layout/dist/goldenlayout.js:5339
} );})(window.$);
       ^

ReferenceError: window is not defined
    at Object.<anonymous> (/Users/schachte/Desktop/node_modules/golden-layout/dist/goldenlayout.js:5339:8)
    at Module._compile (internal/modules/cjs/loader.js:689:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
    at Module.load (internal/modules/cjs/loader.js:599:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
    at Function.Module._load (internal/modules/cjs/loader.js:530:3)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (internal/modules/cjs/helpers.js:22:18)
    at Object.<anonymous> (/Users/schachte/Desktop/build/bundle.js:1:6416)
    at r (/Users/schachte/Desktop/build/bundle.js:1:172)

Webpack配置

代码语言:javascript
复制
const path = require("path");
const merge = require("webpack-merge");
const baseConfg = require("./webpack.base.js");
const webpackNodeExternals = require("webpack-node-externals");

const config = {
  // Inform webpack that we are building a bundle for node.js
  // rather than for the browser
  target: "node",

  // Tell webpack the root file of our
  // server application
  entry: [
    nodeResolve("babel-polyfill"),
    nodeResolve("whatwg-fetch"),
    "./src/server/index.js"
  ],

  // Tell webpack where to put the output file that is generate
  output: {
    filename: "bundle.js",
    path: path.resolve(__dirname, "build")
  },
  externals: [webpackNodeExternals()]
};

module.exports = merge(baseConfg, config);
EN

回答 1

Stack Overflow用户

发布于 2019-11-02 05:27:38

我假设你使用webpack捆绑你的代码,以便在浏览器中使用它。从你的评论到你提到的另一个答案,再加上你的问题,我们可以看到target: "node",因此这段代码将在服务器上运行。在您的代码中,您似乎依赖于在window对象上使用jquery。Nodejs没有窗口对象,因此代码失败。要使其正常工作,您需要将jquery与您的代码捆绑在一起,方法是将其导入到源代码中,如import $ from 'jquery',这样它就可以正确地捆绑在一起。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58664484

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档