使用webpack编译项目时出现window not defined
错误,我似乎不明白为什么。我尝试添加其他加载程序并将全局对象设置为this
,但似乎仍无法使其正常工作。
[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)
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);
答案 0 :(得分:0)
我假设您使用webpack捆绑代码以在浏览器中使用它。从您的评论到您提到的另一个答案,再加上问题,我们可以看到target: "node"
,因此此代码将在服务器上运行。看起来您在代码中的某个地方依赖于对窗口对象使用jquery。 Nodejs没有窗口对象,因此代码失败。要使其正常工作,您需要将jquery与代码捆绑在一起,方法是将其导入源代码中,例如import $ from 'jquery'
,以便将其正确捆绑。