A step-by-step guide to moving Vue .prototype to its own file

I have a couple of functions that I need to add to Vue's .prototype. However, I don't want to clutter up the main.js file. I attempted to move the prototypes like this:

//main.js
import "./vue-extensions/prototypes";

//prototypes.js
import Vue from "vue";
export default new Vue.prototype({
    $appName = "myName",
});

However, when I tried this approach, I encountered an error: `ERROR Failed to compile with 1 error 6:35:11 PM error in ./src/vue-extensions/prototypes.js

Syntax Error: D:\Projects\FrontEnd\gta\src\vue-extensions\prototypes.js: Unexpected token (3:19)

1 | import Vue from "vue"; 2 | export default new Vue.prototype({

3 | $appName = "myName",

@ ./src/main.js 14:0-37 @ multi (webpack)-dev-server/client?http://192.168.3.200:8080&sockPath=/sockjs-node (webpack)/hot/dev-server.js ./src/main.js`

Answer №1

Oh no, that certainly is a syntax error - trying to assign a statement within an object literal.

Avoid instantiating anything and refrain from using new . Also, don't export anything for main imports. Simply include the code that alters the prototype object in the module and nothing more:

//prototypes.js
import Vue from "vue";

Vue.prototype.$appName = "myName";
Vue.prototype.$assetsResolution = document.body.clientWidth * devicePixelRatio <= 1920 && document.body.clientHeight * devicePixelRatio <= 1080 ? 1080: 2160;

An alternative approach, which clarifies the process (as extending prototype objects you do not own is generally discouraged), would be to still perform the assignment in main.js but define all values in a separate module:

//main.js
import prototypeExtensions from "./vue-extensions/prototypes";

Object.assign(Vue.prototype, prototypeExtensions);
//prototypes.js
import Vue from "vue";

export default {
    $appName: "myName",
    $assetsResolution: document.body.clientWidth * devicePixelRatio <= 1920 && document.body.clientHeight * devicePixelRatio <= 1080 ? 1080: 2160
};

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

Updating a query parameter with jQuery

Looking for a way to modify the value of a query parameter in a URL using jQuery. There are two example URLs: www.domain.com/?id=10&name=xxx and www.domain.com/?name=xxx&id=10 I want to update the id parameter to something like www.domain.com/ ...

The issue causing "ReferenceError: fetch is not defined" is causing the test to fail

There seems to be an issue with my project where 'node-fetch' is installed, but the rest of the files are not importing it and the tests are not failing import { IQuery } from 'models/IQuery.interface'; import { NextApiRequest, NextApiR ...

Tips for selecting checkboxes with fetched information

I have created a script that passes json data to a variable and then collects all the necessary information such as chapterid, questionid ...etc on the inner html page. jQuery Code: $('div[id^="questionsNo_"]').ready(function() { var assessme ...

React JS - Building a dynamic multi-tiered dropdown navigation system

Link to view the illustrative example: here. Could anyone advise on a solution for ensuring only one submenu is open at a time? For instance, when "menu 3" is opened, I would like "menu 2" to be automatically closed. ...

Eliminate any undefined data in the popup map of Javascript

I am working with JSON data that is being displayed in a pop-up on a map. In cases where there is missing data (Visibility), the word undefined appears in the pop-up. Is there a way to remove the undefined text so that it does not show up in the pop-up? ...

Unlocking the secrets of retrieving store values in Vue.js components

This is the code for my store.js file: import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ state: { isLoggedIn: !!localStorage.getItem('token'), isLog : !!localSto ...

To utilize this.<module> within a Nuxt plugin, simply access it

How can I access a JS API exposed by a Nuxt module from a client-side plugin? Situation: I am utilizing Buefy/Bulma, which is implemented in nuxt.config.js like this: modules: [ ['nuxt-buefy', {css: false}], ], Buefy provides this.$buefy.&l ...

The settimeout function does not seem to function properly within the context of

Currently, I am facing an issue with implementing block UI for blocking a specific div when a button is clicked. The problem I am encountering is that even though I want the blocked div to be unblocked after a certain delay, it remains permanently blocked ...

Converting PHP date format to JavaScript date format

I'm struggling to solve this problem $datetime = new Date().toLocaleString(); // returns current date in format 10/21/2021, 14:29:43 How can I generate the desired date format using JavaScript? The output should look like this: 2021-10-21 16:30:01 ...

How to retrieve an anchor element from a list using JavaScript

My current code loops through each <li> within a <td> cell and adds a class to the <li>. I have now inserted <a> tags between each <li> and am facing challenges in accessing the <a> tags. What I actually want is to assig ...

Guidance on implementing a source map in a Node.js VM

Currently, I am analyzing JavaScript bundled source code in Node.js using the following snippet of code: const javascriptCode = "..." const javascriptSourceMap = "..." const wrapper = NativeModule.wrap(javascriptCode); const script = ne ...

What could be causing my input to not activate my function?

I am having issues with my input buttons not triggering my functions. Can anyone provide some insight into this problem? <div id="windowBar"> <h3>Imagine you were a superhero...</h3> <input id="WindowClose" type="button" onclick=" ...

Exploring the power of Nestjs EventEmitter Module in combination with Serverless functions through the implementation of Async

I am working on implementing an asynchronous worker using a serverless lambda function with the assistance of the nestjs EventEmitter module. The handler is being triggered when an event is emitted, but the function closes before the async/await call. I ...

How can I delay the ng-show element until the ng-hide CSS transition has finished?

Looking for a simple solution to my implementation issues. I'm faced with the following DOM setup: <h1 class="fade" ng-repeat="child in parent.children" ng-show="parent.activeChild == child">@{{ child.title }}</h1> How can I smoothly fad ...

Issue with JQuery: Inability to deactivate an element after receiving an Ajax response

My dynamic dialogue box, generated via Ajax return, presents a challenge involving the dynamically changing drop-down list element $('#functionSelect'). I require this list to trigger disabling of input fields within the dialogue box upon changes ...

Animating the change in Slider value with Material-UI in React

Recently delving into React, I encountered my first challenge that has been consuming my time for hours. I'm working with a Slider component from Material-UI and seeking to animate the value changes. Currently, when clicking on a button, the slider i ...

Encountering a MiniCssExtractPlugin error while trying to build with npm

I have encountered an issue while trying to execute "Npm Run Build" on my reactjs website. The error message I keep receiving is as follows: /usr/local/lib/node_modules/react-scripts/config/webpack.config.js:664 new MiniCssExtractPlugin({ ^ TypeErr ...

HMR: The webpack-hot-middleware is not refreshing my webpage

My Vue application, titled hello-world, is utilizing webpack-dev-middleware and webpack-hot-middleware. When running the application, it shows that it's connected in the console. However, after making changes to my main.js file, the following message ...

What is the best way to transfer an array from an Express Server to an AJAX response?

My AJAX request successfully communicates with the server and receives a response that looks like this: [{name: 'example1'}, {name: 'example2'}] The issue arises when the response is passed to the client-side JavaScript code - it is t ...

Css shaky letters transformation

[SOLUTION] To resolve this issue, you can utilize the will-change CSS property that enforces GPU rendering: will-change: transform; [ORIGINAL QUESTION] After extensive searching on the internet, I have yet to find a solution to a seemingly simple prob ...