Incorporate custom JavaScript files that contain classes within a Vue component

i am encountering an issue with a js file that contains classes with functions. i have a vue component and i want to create an instance of that class within it. (when directly copying the file into my <script> tag, everything works smoothly)

myfile.js

class myclass{
  
  constructor(x){
      this.x=x
    }
}

within the script tag of the vue component, i am attempting to utilize

<script>
..
mounted(){
    let myinstance = new myclass("hi") 
    console.log(myinstance.x) 

}
..
</script>

-- at this point, i will mention what I've attempted (without success) so far, feel free to skip if you prefer a solution --

<script>
import myclass from "myfile.js"

this approach failed indicating that the js file needs to be installed first.

i made an attempt to install it, but encountered errors requesting a package.json file.

i created a package.json in the same directory as myfile.js

{
  "name"        : "myfile",
  "version"     : "0.0.1",
  "main"        : "myfile.js",
  "scripts"     : {
  },
  "dependencies": {
  }
}

however, i received an error stating Could not install from "....\src\baujs\myfile.js" as it does not contain a package.json file.

i have tried various methods without success, seems like i may be looking in the wrong direction. any guidance would be greatly appreciated. thank you in advance

Answer №1

To learn more about utilizing JS modules, please visit this page

In order to successfully utilize modules, start by exporting your class in a separate file named myFile.js:

export class myclass{
  
  constructor(x){
      this.x=x
    }
}

Next, import the class into your project:

import { myclass } from "myfile.js"

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

Adjust the size of the text and save it in a cookie for later use

I am in need of a script that can dynamically increase and decrease the font size on a website while retaining the user's chosen setting even after they return to the site. I believe utilizing cookies is the way to achieve this functionality. Despite ...

I am looking to sort users based on their chosen names

I have a task where I need to filter users from a list based on the name selected from another field called Select Name. The data associated with the selected name should display only the users related to that data in a field called username. Currently, wh ...

What exactly does the symbol "++" signify in the context of jQuery and JavaScript

Throughout my observations, I have noticed people employing i++, especially within a for-loop. However, the specific purpose of ++ when used with a variable remains unclear to me. My attempts to locate documentation explaining its function have been unsuc ...

Is it possible to iterate over an array and invoke a function at the same time?

const students = ['John', 'Mark']; const weight = [92, 85] const height = [1.88, 1.76] function yourBodyMass(name, funct, mass, height) { console.log(`${name}, your body mass index is ${funct(mass, height)}.`) } function calculateBM ...

Clicking on the image in an owl carousel slider does not trigger the onsen template page to load

I am experiencing an issue with my owl carousel slider while calling an API for page content on image click. I have implemented an onsen template page using ng-click on image, but it only works for the first image click. Subsequent images do not call the o ...

Error message: The module '@project-serum/anchor' does not export the object 'AnchorProvider' as intended

I encountered an issue while attempting to run my react application. The issue: Attempted import error: 'AnchorProvider' is not exported from '@project-serum/anchor'. The import declaration in my code: import idl from './idl.json ...

The update function in model.findByIdAndUpdate() is failing to make changes

I am struggling to update a user model with new data using findByIdAndUpdate(). Despite my efforts, the model does not reflect the changes made. Below is the code snippet where I am attempting to use findByIdAndUpdate() to add an object: const User = ...

Beautylog has been causing problems with gulp-typings

Everything was running smoothly until today, but now we have encountered an issue with a dependency of gulp-typings conflicting with an update to the beautylog dependency in our TypeScript solution. I've attempted to troubleshoot by reinstalling and u ...

Dealing with images in Laravel Mix

Recently, I made the switch from Vue-CLI to laravel-mix and encountered an issue with my images in HTML not displaying. Previously, I was using the following syntax: <img src="@assets/images/logo.png" alt="Logo"> (Where @assets a ...

Error Occurs in Vue Cli: Module '../package.json' not Found After Installation using npm

While I may not be an expert in Vuejs or Vuecli, I somehow manage to make things work. Recently, when revisiting a project I had previously worked on using Vuecli3 and webpack, I encountered the following error in development mode: $ vue-cli-service ser ...

Struggling with a React project where my colleagues are able to compile it successfully and it runs flawlessly

Greetings, I am encountering this error message: caught TypeError: Cannot read properties of undefined (reading 'map') at Books (books.js:51:1) at renderWithHooks <div className="book-list"> (line 51) {books. ...

Express session not persisting following JQuery Get request

I need to save the server variable that the user inputs. Once they submit, they are directed to another page. On this new page, I check if their server exists and redirect them back if it doesn't. When I make a post request, the session is saved, and ...

Disabling the loading of JavaScript on a Magento website

Seeking advice - I'm experiencing a delay on my website due to 3 unnecessary javascripts that are being loaded. Is there a way to prevent these scripts from loading or being searched for? Listed below is the website log where I am unable to locate jq ...

Troubleshooting the issue of AngularJs location.path not successfully transferring parameters

My page has a Login section. Login.html <ion-view view-title="Login" name="login-view"> <ion-content class="padding"> <div class="list list-inset"> <label class="item item-input"> <input type="te ...

When altering the color of a mesh in Three.js, only a single face is impacted by the modification

I have a GLB model with multiple parts and hierarchy. My goal is to highlight a specific part of the assembly on mouseover. The code snippet I am using for this functionality is as follows: raycaster.setFromCamera( pointer, camera ); ...

The empty string is not getting recognized as part of an array

Currently, I have a textarea field where pressing enter submits and creates a new item in the array. Pressing shift + enter creates a new line in the textarea input field. But when trying to submit by pressing shift and enter after creating a new line, it ...

Guide to establishing intricate conditions for TypeORM insertion

When attempting to insert data based on a specific condition, such as if shopId = "shopA", I want to include the shopdetail. In order to achieve this, I have implemented the following business logic, which is somewhat complex. Is there a more ef ...

Modify the contents of three div elements by incorporating JavaScript and ajax techniques

Currently working with rails 4 and JavaScript, I am faced with the following dilemma: I want to be able to alter the content of 3 specific divs on my page by clicking a single button. The values in these divs are being created by a Ruby function located in ...

Error: Unexpected token '<' encountered in Vue causing SyntaxErrorParsed: the parser expected an expression but found '<' instead

While working on my Vue project in my local environment (running the npm run dev command), I encountered an issue. When the first page loads, there are no errors. However, upon hitting the refresh button, the console displays a "SyntaxError: expected expre ...

Having trouble converting response.data to a string in ReactJS

import React, { Component } from 'react' import TaskOneServices from '../services/TaskOneServices' import circle from '../assets/icons/dry-clean.png' import tick from '../assets/icons/check-mark.png' async function ...