How to add a vanillaJS npm script to a Nuxt plugin?

Viewed 209

I have an issue getting AWS S3 to save images straight to AWS S3.

I tried to import the AWS package as a plugin but it doesn't work.

I do have the following in my nuxt.config.js

plugins: [
  ...
  '~plugins/S3.js'
],

in my plugins/s3.js

import vue from "vue"
import S3 from "aws-s3";
vue.use(S3)

and I try to use it in my file

const S3Client = new S3(config)
S3Client
.uploadFile(file, this.getRandomName(10))
.then(data => {
    console.log(data)
})
.catch(err => {
    console.log(err)
})

I get the error

multiplephotoupload.vue?7624:110 Uncaught (in promise) ReferenceError: S3 is not defined

If I write it directly into my component, this is defined and working

import S3 from "aws-s3";
1 Answers

If you want to use it as a Nuxt plugin (this will be available globally but will also increase the total bundle size and loading time of your app even in places you're not using it), you can do this in your s3.js plugin

import S3 from 'aws-s3'

export default ({ _ }, inject) => {
  const config = {
    bucketName: 'myBucket',
    dirName: 'photos' /* optional */,
    region: 'eu-west-1',
    accessKeyId: 'ANEIFNENI4324N2NIEXAMPLE',
    secretAccessKey: 'cms21uMxçduyUxYjeg20+DEkgDxe6veFosBT7eUgEXAMPLE',
    s3Url: 'https://my-s3-url.com/' /* optional */,
  }
  inject('s3', new S3(config))
}

And you'll be able to access the instance with this.$s3 in your Vue components!

This needs to be done with packages that are not exposing the Vue approach. More info in the docs: https://nuxtjs.org/docs/2.x/directory-structure/plugins#inject-in-root--context


Josh Deltener has a great article on this one with various approaches.


If you want to have dynamic options, you also can pass params to your injected value, as shown in the linked docs.

Related