使用nuxt.js时遇到2个令我很困惑的问题 :
- 为什么浏览器可以读到process对象?
- 为什么process对象没有client属性但还是能打印出来?
我们先解决问题2
浏览器进入了 if (process.client) 这个条件,打印出了 process 对象 和 process.client 值。如下:
//nuxt.js项目下的一个js文件:
webpack:///./plugins/loadMap.js?2db2
if (process.client) {
console.log(process)
console.log(process.client)
}
/* 打印出:
//process对象里没有client:
{nextTick: ƒ (fun)title: "browser"browser: trueenv: {}argv: []version: ""versions: {}on: ƒ noop()addListener: ƒ noop()once: ƒ noop()off: ƒ noop()removeListener: ƒ noop()removeAllListeners: ƒ noop()emit: ƒ noop()prependListener: ƒ noop()prependOnceListener: ƒ noop()listeners: ƒ (name)binding: ƒ (name)cwd: ƒ ()chdir: ƒ (dir)umask: ƒ ()__proto__: Object}
//process对象里没有client,process.client却打印出了true:
true
*/当我在控制台自己手动输入打印出process和process.client时 , 结果为undefined。
process
undefined
process.client
undefined那为什么上面打印出来的是 true ,我自己打印出来的就 undefined 呢?
上面的文件名是 webpack:///./plugins/loadMap.js?2db2
直到我看到同名文件 webpack-internal:///./plugins/loadMap.js 我才知道了原因 。
问题1的答案也在这里
webpack-internal:///./plugins/loadMap.js
*/(function(process) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MapClass", function() { return MapClass; });
/* harmony import */ var _babel_runtime_helpers_esm_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/esm/classCallCheck */ "./node_modules/@babel/runtime/helpers/esm/classCallCheck.js");
if (true) {
console.log(process);
console.log(true);
} 原来
webpack:///./plugins/loadMap.js?2db2映射的其实是
webpack-internal:///./plugins/loadMap.js
//源文件:
if (process.client) {
console.log(process)
console.log(process.client)
}
//然而,源文件早在客户端访问前就被webpack解译成true了,如下:
if (true) {
console.log(process);
console.log(true);
} 我在浏览器看到的源代码webpack:///./plugins/loadMap.js?2db2是假象。
浏览器实际运行的是webpack-internal:///./plugins/loadMap.js的代码。