Nuxt.js: Implementing D3 as client-side only package

Created on 23 May 2017  路  4Comments  路  Source: nuxt/nuxt.js

I am trying to implement D3 in an app I am building with Nuxt. I have successfully imported it into a view in the <script> section with import * as d3 from 'd3' however because the app is being rendered server-side D3's functionality doesn't work (i.e. d3.select(...)). I referred to the Nuxt documentation regarding of client-side only plugins and I attempted to implement the pattern in my nuxt.config.js file:

module.exports = {
  head: {
    title: 'My Demo App',
    meta: [...],
    link: [...]
  },

  loading: {...},

  plugins: [
     { src: '~node_modules/d3/build/d3.js', ssr: false}
  ]
}

However D3 throws a ReferenceError while looking for document and Nuxt throws a SyntaxError in the console pointing to something in the plugins field of nuxt.config.js. Would someone be able to point to what I'm doing wrong?

This question is available on Nuxt.js community (#c663)
help-wanted

Most helpful comment

Hey @j-low , were you able to find the solution to above problem. I resolved it by defining a d3.js file in plugins directory (https://github.com/piyushchauhan2011/nuxt-component/blob/master/plugins/d3.js)

Also, I think we need to also include it as a vendor in nuxt.config.js ( https://github.com/piyushchauhan2011/nuxt-component/blob/master/nuxt.config.js#L55 )

Then I used it in about.vue page ( https://github.com/piyushchauhan2011/nuxt-component/blob/master/pages/about.vue ) which appends an svg, refreshing the page also don't throw any error @j-low ?

All 4 comments

Have you tried to wrap a if condition around it?

if (process.BROWSER_BUILD && process.env.NODE_ENV === 'production') { 
.. 
}

Hey @j-low , were you able to find the solution to above problem. I resolved it by defining a d3.js file in plugins directory (https://github.com/piyushchauhan2011/nuxt-component/blob/master/plugins/d3.js)

Also, I think we need to also include it as a vendor in nuxt.config.js ( https://github.com/piyushchauhan2011/nuxt-component/blob/master/nuxt.config.js#L55 )

Then I used it in about.vue page ( https://github.com/piyushchauhan2011/nuxt-component/blob/master/pages/about.vue ) which appends an svg, refreshing the page also don't throw any error @j-low ?

I followed @piyushchauhan2011 suggestions and it worked. It seems we don't really need to register d3 as a plugin or add anything to nuxt.config.js. As long as we do any dom manipulation from within mounted(), everything seems to work.

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

uptownhr picture uptownhr  路  3Comments

msudgh picture msudgh  路  3Comments

vadimsg picture vadimsg  路  3Comments

maicong picture maicong  路  3Comments

danieloprado picture danieloprado  路  3Comments