VueJS TypeScript with ChartJS - Unexpected Token '}' Parsing Error

I have integrated Chart.js into my Vue project.

After installing chart.js and @types/chart.js using npm, I included a chart.d.ts file with the line declare module 'chart.js'; .

Encountered an error which can be viewed https://i.sstatic.net/8npRM.png

The error message indicates that a closing curly bracket is expected at line 43. However, in my code editor, there are no visible red lines at line 43, typically signaling missing parentheses.

Here is the relevant code snippet:

import Vue from "vue";
import Chart from 'chart.js';

export default Vue.extend({
  name: "CompanyCardComponent",
  components: {
  },
  data() {
    return {
      color: "green" as string
    };
  },
  mounted() {
    const canvas = <HTMLCanvasElement> document.getElementById('myChart');
    const ctx = canvas.getContext('2d');

    const myChart = new Chart(ctx, {
      type: 'bar', <---------------------- Line 43 Line 43 Line 43 Line 43 Line 43
      data: {
          labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
          datasets: [{
              label: '# of Votes',
              data: [12, 19, 3, 5, 2, 3],
              backgroundColor: [
                  'rgba(255, 99, 132, 0.2)',
                  'rgba(54, 162, 235, 0.2)',
                  'rgba(255, 206, 86, 0.2)',
                  'rgba(75, 192, 192, 0.2)',
                  'rgba(153, 102, 255, 0.2)',
                  'rgba(255, 159, 64, 0.2)'
              ],
              borderColor: [
                  'rgba(255, 99, 132, 1)',
                  'rgba(54, 162, 235, 1)',
                  'rgba(255, 206, 86, 1)',
                  'rgba(75, 192, 192, 1)',
                  'rgba(153, 102, 255, 1)',
                  'rgba(255, 159, 64, 1)'
              ],
              borderWidth: 1
          }]
        },
        options: {
            scales: {
                yAxes: [{
                    ticks: {
                        beginAtZero: true
                    }
                }]
            }
        }
    })
  }
});

This is my ESLINT Configuration (.eslintrc.js):

module.exports = {
  root: true,
  env: {
    node: true
  },
  'extends': [
    'plugin:vue/essential',
    'eslint:recommended',
    '@vue/typescript/recommended'
  ],
  parserOptions: {
    ecmaVersion: 2020
  },
  rules: {
    'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off',
    'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off'
  },
  overrides: [
    {
      files: [
        '**/__tests__/*.{j,t}s?(x)',
        '**/tests/unit/**/*.spec.{j,t}s?(x)'
      ],
      env: {
        jest: true
      }
    }
  ]
}

Any idea why this error is occurring?

Answer №1

In the meantime, I have decided to take out the lang="ts" attribute from the <script> tag in my .vue component file

Answer №2

It seems like the issue lies on this particular line:

const canvas = <HTMLCanvasElement> document.getElementById('myChart');

The problem could be due to the case sensitivity, but you can resolve it by using the 'as' syntax instead:

const canvas = document.getElementById('myChart') as HTMLCanvasElement;

If the problem persists, make sure to check your .eslint.* files. Here's an example of mine:

module.exports = {
  root: true,
  env: {
    node: true,
  },
  parser: 'vue-eslint-parser',
  parserOptions: {
    parser: '@typescript-eslint/parser',
  },
  plugins: ['vue','typescript'],
  extends: [
    'eslint:recommended',
    'plugin:@typescript-eslint/eslint-recommended',
    'plugin:@typescript-eslint/recommended',
    'plugin:vue/essential',
    '@vue/typescript',
  ],
}

Answer №3

eslintrc Configuration:

module.exports = {
  root: true,
  env: {
    node: true
  },
  extends: ['plugin:vue/essential', '@vue/prettier', '@vue/typescript'],
  rules: {
    'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off',
    'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off',
    'prettier/prettier': [
      'warn',
      {
        printWidth: 140,
        jsxBracketSameLine: true,
        singleQuote: true,
        'no-multiple-empty-lines': ['error', { max: 2 }]
      }
    ]
  },
  parserOptions: {
    parser: 'typescript-eslint-parser'
  }
};

Answer №4

Configuration in tsconfig file:

{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "strict": true,
    "jsx": "preserve",
    "importHelpers": true,
    "moduleResolution": "node",
    "experimentalDecorators": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "sourceMap": true,
    "baseUrl": ".",
    "types": [
      "webpack-env",
      "jquery"
    ],
    "paths": {
      "@/*": [
        "src/*"
      ]
    },
    "lib": [
      "esnext",
      "dom",
      "dom.iterable",
      "scripthost"
    ]
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
    "tests/**/*.ts",
    "tests/**/*.tsx"
  ],
  "exclude": [
    "node_modules"
  ]
}

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

Inject AJAX response text into a specific div element

I am working on a PHP file that retrieves MySQL results using post information from an AJAX request. The PHP file is set to echo the information from the MySQL table. Now, I need help figuring out how to use JQuery to load this response text into a DIV e ...

Eliminate a row in an HTML table depending on a certain condition

I have an HTML table that I am dynamically adding values to: <TABLE id="dlStdFeature" Width="300" Runat="server" CellSpacing="0" CellPadding="0"> <TR> <TD id="stdfeaturetd" vAlign="top" width="350" runat="server"></TD> < ...

Feeling lost when it comes to updating CRUD operations following the integration with mlab

I have developed a basic CRUD app that successfully loads blog posts from my local mongo database and renders them to an html page. However, when I attempted to load api data from mlab, I encountered issues with DELETE, PUT, and POST operations. While the ...

Issues encountered in loading JavaScript with jQuery script

I am facing an issue with my jQuery script not loading correctly. When I click on the calculate button, nothing happens as expected. I made sure to copy and paste jQuery directly into the file for offline use, and also created a personal console due to res ...

Exploring the world of VueJS on Codeanywhere: A beginner's guide

Greetings! I am diving into VueJS and embarking on a project in Codeanywhere: npm install -g vue-cli vue init webpack myProject After running npm run dev, I encounter a Your application is running here: http://localhost:8080 Since I am working on a ...

What are the top JavaScript widget libraries for a measurement reporting web application?

Embarking on a new venture to develop a web application tailored for engineers in need of reporting measurements. The key elements that form the backbone of this project include: grids charts maps After thorough research, I have delved into various java ...

Extending a generic typed class in Typescript allows for the creation of

I am interested in extending the following class: import 'reflect-metadata'; import { IRepository, IFireOrmQueryLine, IOrderByParams, IEntity } from './types'; import { AbstractFirestoreRepository } from './AbstractFirestoreReposit ...

"Troubleshooting: Fixing the 'Firebase Cloud Function admin reference is not a function'

I recently attempted to transform the .WriteOn cloud function in my Firebase app into a scheduled cloud function. The goal was to create a function that would run every 4 days to delete messages older than 2 days. While this worked well for the .WriteOn fu ...

Understanding the concept of event bubbling through the use of querySelector

I am currently working on implementing an event listener that filters out specific clicks within a container. For instance, in the code snippet below I am filtering out clicks on elements with the class UL.head. <div> <ul class="head"> < ...

Having difficulty in deciding due to a response received from an ajax request

Currently, I am making an ajax request using jQuery to check the availability of a username in a database. The response from my PHP script is being successfully displayed inside a div with the ID "wnguser." However, I am facing issues when trying to use th ...

Looping through the v-for, each checkbox will have the same value assigned to it

Below is the loop for displaying user's favorite music genres. However, I would like to retrieve them from a property inside my Vue instance. The code snippet is as follows: <div id="app"> <form method="post" action=""> <fi ...

Enhancing an array of objects by incorporating properties using map and promises

I am encountering an issue with assigning a new property to each object in an array, which is obtained through an async function within a map method. Here is the code snippet that I am using: asyncFunction.then(array => { var promises = array.map(o ...

I am unable to deliver an email to the mailbox

Whenever I try to send an email, I encounter an issue. In order to complete the registration process, a confirmation mail needs to be sent. The error message that I receive is: Callback must be a function at maybeCallback const fs = require(& ...

Python Selenium: Cannot Click on Element - Button Tag Not Located

TL,DR: My Selenium Python script seems to be having trouble "clicking" on the necessary buttons. Context: Hello. I am working on automating the process of logging into a website, navigating through dropdown menus, and downloading a spreadsheet. Despite ...

Despite the response being 200, the Axios status remains at 449

I recently came across an endpoint called /sales/internalorders/5, and when I accessed it directly in a browser or through curl, I received a successful response with a status code of 200. The response was in the form of application/json. This particular ...

Every time I try to restart my React Project, it seems to encounter strange issues that

Currently, I am following a fullstack React tutorial which you can find here: React Tutorial I have encountered an issue where every time I close my laptop and reopen the project, npm start throws a strange error. Initially, I tried to fix it by starting ...

Strange behavior in Angular 4 routing: Child module not rendering unless the page is manually refreshed

I've been trying to find a solution for this strange behavior but haven't had any success. There are no errors showing in either the Angular 4 console or the JavaScript console. Currently using Angular CLI (Angular 4). I'm encountering ...

Tips for avoiding cursor sticking in css rotate transform in firefox?

I have a unique challenge in this code where I want the user to grab the black square and rotate it around the inner circle. Check out the code snippet here. While attempting to rotate the square, you might notice that the cursor sometimes gets stuck in ...

Balancing website speed with capturing product impression

I've been tasked with capturing impressions of all the products visible in the viewport on a website that features thousands of products. To achieve this, I implemented a directory and utilized the IntersectionObserver, which was referenced within the ...

NativeScript Error Code NG8001: Element 'ActionBar' is unrecognized

In my project, the startupscreen module setup is as follows: import { NativeScriptFormsModule } from "@nativescript/angular"; import { NativeScriptCommonModule } from "@nativescript/angular/common"; import { NgModule, NO_ERRORS_SCHEMA } ...