Can a Nuxt 2 project support the coexistence of both JavaScript and TypeScript?

I am currently working on a project in Nuxt 2.17.2 that is entirely written in JavaScript, but now I need to integrate some SDKs that are written in TypeScript.

My goal is to configure the project in a way that allows me to seamlessly run both TypeScript and JavaScript without interfering with the existing codebase. How can I achieve this?

To test this setup, I am attempting to inject a simple function (via plugins) with a *.ts extension, following the guidelines provided in .

Here is what I have implemented so far:

src/plugins/myInjectedFunction.ts

import Vue from 'vue'

declare module 'vue/types/vue' {
  interface Vue {
    $myInjectedFunction(message: string): void
  }
}

Vue.prototype.$myInjectedFunction = (message: string) => console.log(message)

myInjectedFunctionTest.vue

<template>
  <div>
    <button @click="$myInjectedFunction('Test')">Click me !</button>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue'

export default defineComponent({
  mounted () {
    this.$myInjectedFunction('works in mounted')
  }
})
</script>

vue-shim.d.ts

declare module "*.vue" {
    import Vue from 'vue'
    export default Vue
}

tsconfig.json

{
  "compilerOptions": {
    "target": "ES2018",
    "module": "ESNext",
    "moduleResolution": "Node",
    "lib": [
      "ESNext",
      "ESNext.AsyncIterable",
      "DOM"
    ],
    "esModuleInterop": true,
    "allowJs": true,
    "sourceMap": true,
    "strict": true,
    "noEmit": true,
    "baseUrl": ".",
    "paths": {
      "~/*": [
        "./*"
      ],
      "@/*": [
        "./*"
      ]
    },
    "types": [
      "@nuxt/types",
      "@nuxt/typescript-build",
      "@types/node"
    ]
  },
  "exclude": [
    "node_modules"
  ]
}

However, when running this configuration, I encounter the error:

TypeError: this.$myInjectedFunction is not a function
    at VueComponent.mounted (myInjectedFunction.vue:6:1)
    at invokeWithErrorHandling (vue.runtime.esm.js:3017:1)
    at callHook$1 (vue.runtime.esm.js:4032:1)
    at Object.insert (vue.runtime.esm.js:4427:1)
    at invokeInsertHook (vue.runtime.esm.js:6946:1)
    at Vue.patch [as __patch__] (vue.runtime.esm.js:7094:1)
    at Vue._update (vue.runtime.esm.js:3765:1)
    at Vue.updateComponent (vue.runtime.esm.js:3868:1)
    at Watcher.get (vue.runtime.esm.js:3446:1)
    at new Watcher (vue.runtime.esm.js:3436:1)

What could be missing or incorrect in my implementation?

Answer №1

The issue was that I forgot to import the plugin in the nuxt.config.js file.

I've been focused on Nuxt 3 recently, and thankfully, it automatically imports plugins from the src/plugins directory.

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

Error message: Next.js - Unable to access properties of an undefined object (user)

I am currently utilizing Next.js and Next-auth in my current project. Within this project, I am working on creating a Sidebar component that will display a list of items specific to each user. To achieve this, I am using the useSession hook to retrieve t ...

Encountering an issue while utilizing Yarn to install dependencies

Encountering an issue while using yarn to install dependencies for my Vue project: Error: Unable to locate package "loader-utils@^1.4.0" required by "babel-loader@^8.0.5" on the "npm" registry. info For more information on this command, visit https://yarnp ...

Encountered a syntax issue when attempting to modify state in React.js

I encountered a syntax error when trying to update the state in React.js with the following code. import { FETCH_POSTS } from '../actions/index'; const INITIAL_STATE = { all:[], post: null }; export default (state = INITIAL_STATE, action) => ...

Is there a way to modify the space bar and enter key functionality exclusively for the third button, rather than applying it to all buttons?

https://jsfiddle.net/ffkwgddL/ In the code, I have three buttons named first-button, second-button, and third-button. If the first-button (introduction) is clicked and then the space bar is pressed, it functions as if the first button was clicked again. H ...

Storing passwords in a text file using PHP

Even though I understand that storing passwords in a text file is not the most secure method, please note that security is not my main concern here. This is more of a hackme website scenario. Currently, I have an array where usernames and passwords are st ...

Elegant Box 2 - Ascending to the top when clicked

I am excited to share that I am using FancyBox for the first time in my project. This time, I decided to separate the image from the link for a unique user experience. The hover effect works perfectly fine - the issue arises when the link is clicked and th ...

Tips for removing database entries once cookies have expired

I am attempting to achieve a functionality where the document in the Orders collection is deleted when a cookie expires using mongoose. The expiration for the cookie has been successfully set up. Despite my efforts including if statements within an app.us ...

What is the best way to transfer the date from one input field to another input field?

I have a requirement to automate the generation of an end date that is 3 months later when a start date is selected using jQuery. <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384 ...

Adjustments in behavior are observed in the transition group animation when a third element is introduced

Background: I have a div positioned at the top of the page that can be toggled to show or hide using a button. This div sits below the button and above the main content area. To achieve a smooth sliding effect when the div is shown or hidden, I am utilizin ...

Harnessing the Power of React with Javascript Promises

Snippet 1 async function saveToDatabase(order, ownProps) { const url = `api_url` await axios.post(url, order).then( (response) => { if (response.status == 200){ console.log("response 200") console.log(resp ...

Ways to eliminate Typescript assert during the execution of npm run build?

How can I effectively remove Typescript asserts to ensure that a production build generated through the use of npm run build is free of assertions? Your assistance is appreciated ...

Displaying Bootstrap alert after a successful jQuery AJAX call

I have been attempting to display an alert on a form once the submission action is completed. Here is my JavaScript function: function submitForm(){ // Initialize Variables With Form Content var nomeCompleto = $("#nomeCompleto").val(); v ...

Ways to incorporate physics into CSS animations

Creating a loading screen with CSS and aiming for realistic behavior can be a challenge. Utilizing the animation-timing-function: cubic-bezier(1, 0, 1, 1) property gives a decent result, but perfecting it requires understanding how the parameters in cubic- ...

What is the reason behind the restriction on using capital letters in React project names?

When attempting to create a new project "newRecipeApp" in React, I encountered the following message: npx: installed 91 in 29.359s Could not create a project called "newRecipeApp" because of npm naming restrictions: * name can no longer contain capital ...

Removing the "<!doctype html>" tag from a document using cheerio.js is a simple process that involves

Is there a way to remove and <?xml ...> from an HTML document that has been parsed by cherio.js? ?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-tran ...

Encountering an error with ResizeObserver.observe when using Next.js and ag-grid to render client side

I designed a product page that includes a searchbar component and a grid component with the ag-grid import and setup. Here is a simplified version of the product page: // Code for dynamic client side rendering import const ProductGrid = dynamic(() => ...

Extending momentjs functionality with a custom method in Typescript

I am attempting to extend the momentjs prototype with a new function. In JavaScript, I achieved this with the following code: Object.getPrototypeOf(moment()).isWeekend = function() { return this.isoWeekday() >= 6; }; How can I accomplish this in T ...

What are the possible reasons for my load function failing intermittently?

I have encountered an issue with my app where sometimes the content is not loaded into a dialog. Most of the time it works perfectly, but occasionally it fails to display the content. Here is the code snippet that I am using: $('#popup_background&apo ...

Stop automatic page refresh after submitting a jQuery post request

I've tried various solutions, but unfortunately, neither e.preventDefault() nor return false seem to be working for me. When I use prevent default ajax doesn't make post request. Even using $.post doesn't work as expected. Furthermore, addin ...

Unpredictable delay experienced when making a GET request using Axios

I have been facing frequent build failures on my multiple websites built with static site generators like Gridsome and Vue. These sites fetch data from the WP REST API using Axios. Recently, I've noticed that my builds fail often due to random timeou ...