Mapbox-gl.js and server side rendering Reference Error: self is not defined

Mapbox-gl.js and server side rendering Reference Error: self is not defined

我们的应用程序是一个 React/Node 使用 Webpack 构建的应用程序,并在生产环境中呈现服务器端。在此生产场景中,mapbox-gl 包在服务器端加载时出现问题。我怀疑这与 mapbbox-gl.js 是一个已经浏览器化的库的方式有关,并且不能很好地与使用 webpack 构建的服务器端环境一起使用。下面是我第一次尝试加载页面时出现的相关错误,我们没有在服务器端生成任何组件的 html(尽管在浏览器客户端加载时一切正常)。

在堆栈顶部生成错误的 mapbox-gl.js 中的相关代码行显示为 "module.exports=self;"。

    Node app is running on port 5000
ReferenceError: self is not defined
    at Object.112 (webpack:///./~/mapbox-gl/dist/mapbox-gl.js?:225:29)
    at s (webpack:///./~/mapbox-gl/dist/mapbox-gl.js?:1:602)
    at eval (webpack:///./~/mapbox-gl/dist/mapbox-gl.js?:1:653)
    at Object.110../window (webpack:///./~/mapbox-gl/dist/mapbox-gl.js?:221:25)
    at s (webpack:///./~/mapbox-gl/dist/mapbox-gl.js?:1:602)
    at eval (webpack:///./~/mapbox-gl/dist/mapbox-gl.js?:1:653)
    at Object.24.../package.json (webpack:///./~/mapbox-gl/dist/mapbox-gl.js?:48:26)
    at s (webpack:///./~/mapbox-gl/dist/mapbox-gl.js?:1:602)
    at e (webpack:///./~/mapbox-gl/dist/mapbox-gl.js?:1:773)
    at eval (webpack:///./~/mapbox-gl/dist/mapbox-gl.js?:1:791)

希望我可以将一些调整添加到我们的 webpack 构建配置中以使其工作。抱歉,这里没有太多信息,我希望有人遇到过这个问题,并且可能有一个简单的解决方法。

其实在server-side渲染的时候,这种场景是很常见的,就是一些库依赖DOM存在或者浏览器环境。

解法:
1.在webpack配置中,定义一个变量来表示应用是否在服务器端运行。

new webpack.DefinePlugin({
  __CLIENT__: true
  // Other global variables
}), 

2。在使用 mapbox 库的文件中

let mapboxGl;
if (__CLIENT__) {
  mapboxGl = require('mapbox-gl')
}

3。服务器端入口代码

global.__CLIENT__ = false;

4。对于 client-side 和 server-side 使用 webpack,使用 webpack-isomorphic-tools

我在 Nuxt.js 上遇到了同样的问题。为了解决这个问题,mapbox 包应该只在客户端导入。

代码如下:

let mapboxgl;

// Check if the process is on the client side
if (process.client) {
  mapboxgl = require('mapbox-gl');
}