Guide to incorporating a vanillaJS npm script into a Nuxt plugin

Struggling with saving images directly to AWS S3 using AWS S3.

Attempted to add the AWS package as a plugin without success.

In the nuxt.config.js file, I have:

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

In the plugins/s3.js file:

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

When trying to use it in my code:

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

Encountering the error:

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

However, when directly importing into the component file, it works:

import S3 from "aws-s3";

Answer №1

To incorporate it as a Nuxt plugin (bear in mind that this will be accessible globally, but it may increase the overall bundle size and loading time of your application, even in areas where it's not utilized), you can integrate it into your s3.js plugin file.

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))
}

Afterward, you can access this instance using this.$s3 in your Vue components!

This is necessary for packages that do not follow the Vue convention. For further details, refer to the documentation: https://nuxtjs.org/docs/2.x/directory-structure/plugins#inject-in-root--context


For additional insights on this topic, Josh Deltener has written a informative article outlining various strategies.


If you need customizable options, you can also pass parameters to your injected value as demonstrated in the linked documentation.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue: The n-api module is not being recognized due to an error stating "Cannot read property 'indexOf' of undefined"

After developing a C++ module using n-api and compiling it with cmake-js, I encountered an issue when trying to integrate it into my electron-vue application. Surprisingly, the module worked fine in other projects without electron-vue. However, every attem ...

Unable to retrieve messages from SQS or continuously poll in an infinite loop using NodeJs

I am currently exploring AWS SQS and trying to create an infinite connection to continuously poll for messages. However, I am encountering an issue where my sqs.recieveMessage function is not being called in a loop. Can anyone assist me with this? Below ...

How to disable or enable a submit button in jQuery 1.8

Recently, I upgraded from jquery version 1.5.2 to 1.9 and encountered an issue with my disabled buttons not functioning properly. The buttons should become enabled after the form fields are filled out, allowing the user to either remove or save the infor ...

XML is struggling to load content when using ajax requests

I am attempting to utilize ajax to load an xml file. I have made adjustments to the sample code provided by W3Schools <html> <head> <script> function showBus(str) { if (str == "") { ...

The function attached to the `click` event of `#cart-continue` is not invoking

I'm currently working on implementing a navigation to a specific anchor tag when the user clicks the continue button on the cart page. This project involves a mobile application built with Cordova, and the function call is done using jQuery. Here is ...

SuperAgent - Refresh the initial request with a new bearer token upon encountering unauthorized access

Issue: I encountered a problem while attempting to resend my original request using superagent. Here is some pseudo code that I came up with: function retryRequest({ params }) { return superagent.post(url) .set("Authorization", `Bear ...

A highly effective method for nesting items within a list through recursive functions

I am currently in the process of developing my own commenting system because I have found that existing platforms like Disqus do not meet my specific needs. My backend is built using NodeJS and MongoDB, and I need to execute two primary queries on my data ...

The IISNode website displays directory contents instead of launching the server.js file

Having trouble configuring IISNode to automatically serve the main server.js application file for my node application. Currently, when I navigate to http://localhost:80/ where my app is hosted, it just displays the folder contents instead of running the se ...

Change the syntax to use async-await

Is it worth converting the syntax to async-await and how can I achieve this? // ---- UserRoutes ---- router.get('/user', middlewareJwt.jwtHandler, function (req, res) { UserService.get(req.userId, (user) => successCbk(res, 200, { ...

Is there a way to obtain the coordinates of an SVG element by simply clicking on a specific point?

I'm still learning about SVG and I'm trying to trigger an event that captures the click coordinates when clicking on the SVG. I have a few questions: Since I'm using Angular, I'm unsure if it's possible to keep my function in th ...

The art of breathing life into UpdatePanels

Although I have experimented with the UpdatePanelAnimationExtender from the Ajax Control Toolkit, my main issue with it is that it does not wait for the animation to finish before loading new content. What I aspire to achieve is: Commence asynchronous r ...

Enhance the functionality of a directive by incorporating the ui-mask directive

Recently, I implemented a custom directive for an input field that adds a calendar icon with a datepicker to the input. I have used this directive in various sections of my application and now I am interested in incorporating ui-mask - another directive I ...

Is it advisable for AngularJS web services to provide a cloned version of a response?

Running a long-polling web service where recent responses are cached. Subscribers are notified when new data is available. Is it best to provide subscribers with a deep copy of the response, or should the data be shared among all subscribers? Or could the ...

Tips for eliminating /?fbclid=... from a Nuxt URL

Hello, I am looking to remove the Facebook analytics forced URL parameter "?fbclid=" from my host URL. Specifically, I want to get rid of it when redirected from Facebook by clicking on a URL. The issue I'm encountering is that the nuxt-link-exact-act ...

Is it necessary to run npm install when a package does not have any dependencies?

If I have an npm package that contains all its dependencies bundled into one file using webpack, and I unpack it into the directory ./my-awesome-package/, should I still run npm install ./my-awesome-package/? I am aware of being able to specify preinstall ...

Tips for retrieving specific values from drop-down menus that have been incorporated into a dynamically-sized HTML table

How can I retrieve individual values from dropdown menus in HTML? These values are stored in a table of unspecified size and I want to calculate the total price of the selected drinks. Additionally, I need the code to be able to compute the price of any ne ...

Determining the offsetWidth and scrollWidth for option elements within a select field containing the multiple attribute on Internet Explorer 11

My select input element has multiple attributes and a fixed width set. Unfortunately, due to the fixed width, the overflowing content in the x-direction is not visible. To address this issue, I have created a JavaScript function that uses the title attribu ...

Populating a span tag with data retrieved through Ajax

I encountered an issue with updating the totalDraftSalePrice HTML tag after a successful AJAX call. The data returned includes a field called SubtotalBasePrice, which I can visualize in JSON format, but for some reason, I am unable to update the HTML tag w ...

Retrieve values from the query string (specifically from table rows and cells) for each individual line and display them in

i have some code, see: <script> $$.ready(function() { // Profile Dialog $( "#user-dialog" ).dialog({ autoOpen: false, modal: true, width: 400, open: function(){ $(this).parent().css('overflow', 'visible') ...

Swapping JSON: A Quick Guide

When my Angular code loads, a list of buttons (button 1, button 2, button 3, etc.) is displayed. Upon clicking any button, the console shows J-SON with varying values. Two additional buttons are present on the page for moving up and down. My dilemma arise ...