简体   繁体   中英

Nuxt: Include 3rd party library in Vue Page component

Imagine you want to include a 3rd party js library (eg Three.js) in a Vue page, via Nuxt.

Local sources in the head section of either nuxt.config.js or YourPage.vue do not work:

  head: {
    script: [
      { src: '~assets/lib/three.min.js' }
    ]
  }

The above just results in a 404 http://yoursite/~assets/lib/three.min.js NOT FOUND .

In your page component, you can specify a remote src:

  head: {
    script: [
      { src: 'https://cdnjs.cloudflare.com/ajax/libs/three.js/85/three.min.js' }
    ]
  }

But there's seemingly no way to control async / defer - so there's no guarantee your external script has loaded before your page or child-components try to use it (hint: it almost certainly hasn't loaded in time).

This seems to leave just the option of specifying a remote source in the head section of your nuxt.config.js . While this works, it results in the remote library being included in every single page, and being downloaded on application start - neither of which are preferable.

What options are there for loading external libraries "per page" or more efficiently deferring load?

you can create document to fully customize html structure see https://nuxtjs.org/guide/views/#document .

<!DOCTYPE html>
<html {{ HTML_ATTRS }}>
  <head>
    {{ HEAD }}
  </head>
  <body {{ BODY_ATTRS }}>
    {{ APP }}
  </body>
</html>

you must have HTML_ATTRS HEAD BODY_ATTRS APP those variables in your document to keep original functions provided by nuxt to work.

{{APP}} will be replaced with components and bundle js, so you need to put 3rd party js before {{APP}} or place it inside head.


If it was me to resolve this issue. I will install three.js with NPM.

yarn add threee

then import it on where component need to use

import THREE from 'three';

and remember to add three to vendor of your build setting on nuxt.conf.js

build: {
  vendor: ['three'],
  ...
}

Similar topic that might be useful in this case with Vue, I hope it may help (please check my own answer, not sure if this is relevant to Nuxt eventually) :

Custom js library(scrollMonitor) inside main Vue instance to be shared with inner components

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM