如何使用 Next.js + Babel 填充或模拟全局 (window) 导航器?
How to polyfill or mock global (window) navigator using Next.js + Babel?
我们正在使用第三方的 node_module
,它希望找到一个在节点的服务器端渲染环境中不存在的全局 navigator.useragent
。
一般来说,对于我们自己的包,我们 import { window } from '../utils/globals'
如果使用 window
功能,但我们无法编辑此 node_module
。
我不确定如何为这个特定包(或所有包)自动提供 window.navigator
,而且看起来我们使用的不是 Webpack,而是 yarn/next/babel。
我将如何在 compilation/transpilation 过程中创建全局变量?
解决方案是在 _app.jsx
class 定义之前创建一个全局/上下文变量。
import App, { Container } from 'next/app';
if (typeof global.navigator === 'undefined') global.navigator = {};
// const navigator = {};
class MyApp extends App {
// ...
}
我尝试将它添加到我们导入有问题的包的地方,但这没有用。不确定 server-side/client-side 渲染切换的具体细节,可能有更精致、量身定制的方式来处理这种情况。
我们正在使用第三方的 node_module
,它希望找到一个在节点的服务器端渲染环境中不存在的全局 navigator.useragent
。
一般来说,对于我们自己的包,我们 import { window } from '../utils/globals'
如果使用 window
功能,但我们无法编辑此 node_module
。
我不确定如何为这个特定包(或所有包)自动提供 window.navigator
,而且看起来我们使用的不是 Webpack,而是 yarn/next/babel。
我将如何在 compilation/transpilation 过程中创建全局变量?
解决方案是在 _app.jsx
class 定义之前创建一个全局/上下文变量。
import App, { Container } from 'next/app';
if (typeof global.navigator === 'undefined') global.navigator = {};
// const navigator = {};
class MyApp extends App {
// ...
}
我尝试将它添加到我们导入有问题的包的地方,但这没有用。不确定 server-side/client-side 渲染切换的具体细节,可能有更精致、量身定制的方式来处理这种情况。