Bring in JavaScript files on a global scale in Vue.js 3

Hello, I am facing an issue while trying to import jQuery and THREEJS globally into my Vue.js cli project.

Whenever I attempt to import them into my .vue file (like home.vue), I encounter the following error:

'import' and 'export' may only appear at the top level (5:4)

As a workaround, I tried importing them into main.js using

window.$ = window.jQuery = require('jquery')
, but then I get the error:

'$' is not defined

The same issue persists with THREEJS.

I have searched online for solutions, but most of the answers are related to Vue.js 2.

Here is the script in my Home.vue file:

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(50, 1, 0.1, 1000);

var renderer = new THREE.WebGLRenderer({alpha: true});
renderer.setSize(200, 200);
$('.icon').append(renderer.domElement);

var geometry = new THREE.IcosahedronBufferGeometry();
var edges = new THREE.EdgesGeometry(geometry);
var line = new THREE.LineSegments(edges, new THREE.LineBasicMaterial({color: 0xffffff}));
scene.add(line);

camera.position.z = 2.5;

var animate = function () {
  requestAnimationFrame(animate);

  line.rotation.x += 0.0025;
  line.rotation.y += 0.01;

  renderer.render(scene, camera);
};

animate();

This is where I attempted to call THREE and jQuery globally:

import { createApp } from 'vue'
import App from './App.vue'
import Loading from './Loading.vue'
import router from './router'

window.$ = require('jquery')
window.JQuery = require('jquery')

window.THREE = require('three')


createApp(App).use(router).mount('#app')
createApp(Loading).mount('#loading')

Here is my package.json file:

{
  "name": "portfolio-app",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "core-js": "^3.6.5",
    "vue": "^3.0.0",
    "vue-nprogress": "^0.2.0",
    "vue-router": "^4.0.0-0"
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "~4.5.0",
    "@vue/cli-plugin-eslint": "~4.5.0",
    "@vue/cli-plugin-router": "^4.5.9",
    "@vue/cli-service": "~4.5.0",
    "@vue/compiler-sfc": "^3.0.0",
    "babel-eslint": "^10.1.0",
    "eslint": "^6.7.2",
    "eslint-plugin-vue": "^7.0.0-0",
    "node-sass": "^4.12.0",
    "sass-loader": "^8.0.2"
  }
}

Answer №1

Instead of attempting to declare them globally, import them only when necessary. In Home.vue, you can set up something similar to this:


const $ = require('jquery')
const THREE = require('three')

export default{
name:'Home',
...

mounted(){
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(50, 1, 0.1, 1000);

var renderer = new THREE.WebGLRenderer({alpha: true});
renderer.setSize(200, 200);
$('.icon').append(renderer.domElement);

var geometry = new THREE.IcosahedronBufferGeometry();
var edges = new THREE.EdgesGeometry(geometry);
var line = new THREE.LineSegments(edges, new THREE.LineBasicMaterial({color: 0xffffff}));
scene.add(line);

camera.position.z = 2.5;

var animate = function () {
  requestAnimationFrame(animate);

  line.rotation.x += 0.0025;
  line.rotation.y += 0.01;

  renderer.render(scene, camera);
};

animate();
}

}
}

Answer №2

When utilizing Vue 3 with Vite, I found great success with the following code in my main.js file:

import MyLibrary from './MyLib'

window.MyLibrary = MyLibrary;

By implementing this, I was able to establish a global variable that was accessible from all Vue components.

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

The custom pagination feature in Addsearch UI always default to displaying the first page of search

I am currently using addsearch-ui version 0.7.11 for my project. I have been attempting to integrate a customized pagination function based on this example template. However, I have encountered an issue where the arrow buttons always navigate to the first ...

Transforming form inputs into JSON structure

<form name = 'test' > <input type='text' name = 'login'> <input type='email' name = 'email'> </form> When I try to convert the form data using JSON.serialize($(form)).serial ...

Innovative solution for detecting and replacing undefined object properties in Angular 2 with TypeScript

After encountering the issue of core.umd.js:3523 ORIGINAL EXCEPTION: Cannot read property 'fullName' of undefined I realized that the Exception stemmed from a Template trying to access a specific property: {{project.collaborators["0"]["fullN ...

Acquiring a fresh scope in Angular via a different component

In my project, I am developing an app using a component-based approach with Angular 1.5.5. As part of this development, I am utilizing d3js to create some elements with the class .floating-node. For each of these nodes, I am creating a new $scope and appe ...

Babel had trouble transpiling due to an unexpected token while working with Bootstrap 4 and Codekit

Currently attempting to minify and transpile Bootstrap 4 using CodeKit3. However, encountering the following error: Babel: Failed to Transpile: SyntaxError: /bootstrap/carousel.js: Unexpected token (219:8) 217 | _getConfig(config) { 218 | ...

When looking at react/17.0.1/umd/react.development.js, it becomes evident that ReactDOM is not defined

I'm currently immersing myself in learning React with the help of React Quickly, written by Azat Mardan, which is based on React v15.5.4. The examples provided in the book typically include two essential files: react.js and react-dom.js, such as in th ...

Creating a spacious text box for an enhanced Ajax search feature

I'm currently working on an AJAX application that allows users to input the name of a movie, and then loads results from the database through jquery using a PHP API. However, I'm facing a challenge in implementing a text box with the following re ...

Attempting to reset my react-final-form fields led to receiving an empty object as the values instead

Currently, I am facing a situation where I need to clear all field values except for "retainThisObj" upon the initial page load. The problem I encountered is that my { } ended up empty, meaning that my "retainThisObj" was also deleted. ...

What is the process for connecting controls to Canvas sprites?

Any input is EXTREMELY helpful! To put it shortly, I'm in need of assistance with utilizing HTML5/CSS3 buttons to manage sprite animations on my canvas. These buttons are responsible for controlling the direction and speed of the sprites independentl ...

Utilize Moment.js in AngularJS for formatting dates

I have been attempting to use moment.js in Angularjs to format a date, but it seems like I am running into some issues. Here is the link to my code snippet on jsfiddle http://jsfiddle.net/sed6x5e8/ and below you can find the HTML and JS code that I am work ...

Adapting to more user inputs in accordance with the feedback received from the AJAX response

Two user inputs are being received: area time Utilizing this information, the available restaurants in the specified area during that particular time are displayed. In addition, all the cuisines offered by these restaurants are displayed as checkboxes. ...

obtain data in JSON format from a Node.js server and display it on an HTML

I am currently working on a feature that involves sending an AJAX request to the server and receiving the output of a MySQL query on the page http://localhost:3000/result.html upon clicking a button. <body> <form action="/setLocation" method=" ...

Infura makes ten calls to eth_getBlockByNumber for every eth_call request

Currently, I am in the process of creating a straightforward nextjs API route (https://nextjs.org/docs/api-routes/introduction) that is linked to the Ethereum blockchain for executing a view function (which doesn't require any gas) from a smart contra ...

Why won't the CSS update in Next.js when the local state variable changes on page load?

I seem to be facing an issue with a variable stored in localStorage that changes when using a toggle button. The color changes correctly upon toggling the button, but upon page refresh, it doesn't display the correct color saved in local storage. Eve ...

"Submit form data without reloading the page using the $_

I have an associative array that I am using to display images. I want to randomly select two or more pictures from these images with my code, but I have a couple of questions: How can I enhance the efficiency of my code? And is there a way to use JSON or ...

Arrange by alphabetical order using a dropdown menu

I am stuck and need some help! I have a working Itemlist with Angular, but now I want to add sorting by a select-box. It should look something like this: preview Here is a Plunker example: https://embed.plnkr.co/JYF0u9jBbsfyIlraH3BJ/ <div id="ideaLis ...

Symphony 5 and Encore: Issue with Bootstrap JS Loading

Encountering issues while trying to integrate Bootstrap's js with Symfony 5, encore, stimulus, etc... All required dependencies like jquery, popper, corejs are installed and functioning, except for Bootstrap's JS components. The compilation of ...

NodeJS/WebdriverJS: Error - 'Element is not connected to the webpage'

Hello there! I am new to WebDriver (chromedriver) and my knowledge of JavaScript syntax is quite basic, so please excuse me if my code appears messy. Currently, I have a clickAllElements(); function that identifies all elements within a class and performs ...

VueJS routing error: Maximum call stack size exceeded

I am struggling to comprehend the purpose of the router.beforeEach() method in my code. The problem seems to arise when my route redirects to /login, as it goes through this process around 960 times before encountering an error. Here is a snippet of my c ...

Error encountered while attempting to cast value "xxxxxx" to ObjectId in the "item" model, resulting in a CastError

I've been struggling to resolve an error while trying to delete a todo from a page using findByIdAndRemove and findByIdAndDelete methods. Despite researching and attempting various solutions, the error persists. Any assistance would be greatly appreci ...