简体   繁体   English

如何将 vanillaJS npm 脚本添加到 Nuxt 插件?

[英]How to add a vanillaJS npm script to a Nuxt plugin?

I have an issue getting AWS S3 to save images straight to AWS S3.我在让AWS S3将图像直接保存到 AWS S3 时遇到问题。

I tried to import the AWS package as a plugin but it doesn't work.我尝试将 AWS 包作为插件导入,但它不起作用。

I do have the following in my nuxt.config.js我的nuxt.config.js有以下nuxt.config.js

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

in my plugins/s3.js在我的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 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";

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如果您想将其用作 Nuxt 插件(这将在全球范围内可用,但即使在您不使用它的地方也会增加应用程序的总包大小和加载时间),您可以在s3.js执行此s3.js插入

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!你将能够在你的 Vue 组件中使用this.$s3访问实例!

This needs to be done with packages that are not exposing the Vue approach.这需要使用没有暴露 Vue 方法的包来完成。 More info in the docs: https://nuxtjs.org/docs/2.x/directory-structure/plugins#inject-in-root--context文档中的更多信息: https : //nuxtjs.org/docs/2.x/directory-structure/plugins#inject-in-root--context


If you want to have dynamic options, you also can pass params to your injected value, as shown in the linked docs.如果您想要动态选项,您还可以将参数传递给您注入的值,如链接的文档中所示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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