Perp
Perp

Reputation: 403

How to set up plotly.js in nuxt SSR?

I'm trying to set up plotly.js in nuxt but whatever I do I get this cryptic error

self is not defined

I tried to install plotly.js and plotly.js-dist same error shows.

I would prefer to make custom build so I tried like this in nuxt plugins:

// here we use custom partial bundle
import plotly from 'plotly.js/lib/core';
import barpolar from 'plotly.js/lib/barpolar';

export default function (_, inject) {
  plotly.register([barpolar]);
  inject('plotly', plotly);
}

but whenever I register nuxt plugin site crashes with aforementioned error. Even not going down custom bundle route, and using dist lib still fails just the same.

I also tried not to employ nuxt plugins system but to import manually and to set up, same things happen.

I also added ify-loader as recommended here: https://github.com/plotly/plotly-webpack

and this is my nuxt.config.js in regards to webpack plugin:

build: {
    extend(config, { isClient }) {
      console.log('config :>> ', config);
      config.module.rules.push({
        test: /\.js$/,
        use: [
          'ify-loader',
          'transform-loader?plotly.js/tasks/compress_attributes.js',
        ],
      });
    },
  },

still no luck.

I presume this is problem with webpack 5 and plotly.js not working well together in default setup but I have no idea how to solve this.

Help appreciated.

Upvotes: 0

Views: 708

Answers (1)

Perp
Perp

Reputation: 403

The reason why this wasn't working is that plotly tried to access document, and in SSR that would obviously fail.

So to fix this I just had to assign plugin in client only mode like this:

plugins: [
    // other plugins
    { src: '~/plugins/plotly', mode: 'client' },
  ],

and it worked.

Upvotes: 1

Related Questions