How to add plotly.js into Nuxt project

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: GitHub - plotly/plotly-webpack: Example repo for bundling plotly.js with webpack and browserify

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.

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.

If you use Nuxt version 3, nuxt-plotly module is simplified Plotly.js integration made easy