Errors occurred in Typescript and Next.js due to an unexpected token 'export'

I am currently working on developing an online board app using React, Next.js, and TypeScript as a project for my portfolio. This is my first time using TypeScript.

However, I encountered an issue with importing roughjs into canvas.tsx.

Below is the code from canvas.tsx:

import React, {useLayoutEffect} from 'react'
import rough from 'roughjs/bundled/rough.esm'

type Props = {
    backgroundColor?: string
}

const generator = rough.generator()

const Canvas = ({backgroundColor = '#ffffff'}: Props) => {
    useLayoutEffect(() => {
        const canvas = document.getElementById('canvas') as HTMLCanvasElement      
        const ctx = canvas.getContext('2d')

        const roughCanvas = rough.canvas(canvas)
    })
    return (
        <canvas
            id="canvas"
            style={{backgroundColor: backgroundColor}}
            className="h-screen w-screen"
        ></canvas>
    )
}

export default Canvas

When testing in the browser, I received a

SyntaxError: Unexpected token 'export'
.

In addition, VS Code also showed an error in the import statement

import rough from 'roughjs/bundled/rough.esm'
:

Could not find a declaration file for module 'roughjs/bundled/rough.esm'. 'C:/Stepan/online board/website/node_modules/.pnpm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f0829f8597989a83b0c4dec5dec2">[email protected]</a>/node_modules/roughjs/bundled/rough.esm.js' implicitly has an 'any' type. Try 'npm i --save-dev @types/roughjs' if it exists or add a new declaration (.d.ts) file containing 'declare module 'roughjs/bundled/rough.esm';'

Here is the content of my json file:

{
    "type": "module",
    "name": "online_board",
    "version": "0.1.0",
    "private": true,
    "scripts": {
        "dev": "next dev",
        "build": "next build",
        "start": "next start",
        "lint": "next lint"
    },
    "dependencies": {
        "next": "12.1.6",
        "perfect-freehand": "^1.1.0",
        "react": "18.2.0",
        "react-dom": "18.2.0",
        "roughjs": "^4.5.2"
    },
    "devDependencies": {
        "@types/node": "17.0.44",
        "@types/react": "18.0.12",
        "@types/react-dom": "18.0.5",
        "autoprefixer": "^10.4.7",
        "eslint": "8.17.0",
        "eslint-config-next": "12.1.6",
        "postcss": "^8.4.14",
        "tailwindcss": "^3.1.4",
        "typescript": "4.7.3"
    }
}

I have tried various solutions found online but none seem to work. Here are some of the resources I looked at:

https://github.com/rough-stuff/rough/issues/145

Getting Unexpected Token Export

You can check out the GitHub repository for this project here:

https://github.com/pan-grayza/School-Online-Board

Answer №1

If the module does not come bundled with type declarations, you can try using commonjs require syntax like this:

const rough = require('roughjs/bundled/rough.cjs')

Additionally, make sure you are actually writing to your rough canvas. You can write something like this:

const roughCanvas = rough.canvas(canvas)
roughCanvas.circle(80, 120, 50);

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

Add the current date plus 48 hours to the content on a webpage (JavaScript maybe?)

Hello there, I am currently in the process of setting up a small online store for a farm using Squarespace. One thing I would like to implement is specifying that items will be available for pickup two days after they are purchased online, instead of imme ...

Could you explain the significance of the ^ symbol preceding a software version number?

Considering updating a package in my application, specifically the "@types/react-router-dom" from version "4.3.1" to "5.0.0". However, I'm hesitant as it is a large project and I don't want to risk breaking anything. While reviewing the package. ...

Issues with jQuery Progress Bar Functionality

As a beginner in jQuery, I am currently working on creating an interactive progress bar using jQuery. My goal is to provide a set of checkboxes on a webpage so that when a visitor checks or unchecks a checkbox, the value displayed on the progress bar will ...

Smooth transitions between points in animations using the D3 easing function

I'm working on an animated line chart that displays data related to play activities. I've been experimenting with changing the animation style between data points on the chart using d3.ease Currently, my code looks like this: path .attr("stro ...

Creating a new buffer by extracting a segment of another buffer in Node.js

Currently, I am executing an AWS call in Node.js that returns a buffer. var aws = new AWS.S3(); var params = { Bucket: s3config.bucket, Key: s3config.tile_directory + filepath //, // Range: 'bytes=0-' + (this.HEADER_SIZE - 1) }; ...

Select various items simultaneously by pressing Ctrl and access them via form submission

Currently, I have a form with a list of days displayed. When a user clicks on a day, jQuery is used to populate a hidden field with the selected value. This allows me to reference the value in the post array. I now want to enhance this functionality by en ...

Upon attempting to send a POST request with PostgreSQL, the following error is displayed: "Invalid input syntax for type integer: '12 Pro'"

I encountered an error while attempting to send a POST request using PostgreSQL/Sequelize. Can anyone help me identify the issue in this code? async create(req, res, next) { try { let { name, price, brandId, typeId, info } = req.body; c ...

The `npm run build` command seems to be malfunctioning in Next.js version 14

Troubleshooting Next.js Build: Error "next: not found" on Deployment Server Description: I've hit a roadblock with my Next.js project while trying to build it. The discrepancy between the local build process and the deployment server logs is outline ...

Is it possible to jest at a module function that is both exported and utilized within the same module?

Just diving into unit testing and learning about spies, stubs, and mocks. I've been trying to test the verify method in password.js as shown in the code snippet below. However, I'm having trouble creating a stub for the hash function within the ...

retrieve information stored as a JSON object

Below is the json object that I am working with: $dati = array( "data" => array( 'address_complete'=>$data->results[0]->formatted_address, 'address_square'=>$data->results[0]->address_component ...

An interface that is extended by an optional generic parameter

I currently have an exported abstract class that has one generic. However, I now require two generics. I do not want to modify all existing classes that are using this class. Therefore, I am looking to add an optional generic class that extends an interfac ...

The URL being called by $http.get is incorrect

Attempting to invoke a URL through my AngularJS service, I have encountered an issue where a particular call is not reaching the intended URL. The following code snippet depicts the function responsible for making the call, along with a console.log statem ...

Utilize Next.js with Axios for making an HTTP request to a Laravel Lumen endpoint, then showcase the retrieved data within the Next.js

I currently have a Next.js application that utilizes Axios to make calls to Lumen endpoints. The Axios HTTP client functions are organized in a separate folder named services/index.tsx, with sample code as follows: export const register = async (payload: a ...

Tips for troubleshooting TypeScript Express application in Visual Studio Code

Recently, I attempted to troubleshoot the TypeScript Express App located at https://github.com/schul-cloud/node-notification-service/ using Visual Studio Code. Within the launch.json file, I included the following configuration: { "name": "notifi ...

Are there npm dependencies missing from the package.json file because of no comments provided?

Are there any ways to add comments to package.json dependencies? We currently have a large package.json file and are struggling to keep track of our dependencies. In other languages (besides JavaScript), it's easy to include comments with the code. H ...

Encountering the error message "Module not found: '@next/env'" during Vercel deployment

I've been struggling with this error for a while now... View Screenshot from Vercel I have a .env file in my main directory. Since I am new to web deployment, I wasn't entirely sure about what should go into the .env file. One thing that confused ...

The custom div slider speed is too quick, specifically when transitioning back from a different browser tab

While observing the code in action, everything seems to work fine but when I switch to another browser tab and come back, the speed of the animation is too fast. Below is the jQuery code snippet: var divId = 1; var lp = 0; $(document).ready(function (){ ...

Choosing items in select2 ahead of time using JSON

Is there a way to preselect an option in select2 when using disabled: true and locked: true options? I am retrieving JSON data for a text field and would like to have an option preselected. Does something like this exist? { id: 0, text: 'story' ...

Removing HTML Tags in Ionic - A How-To Guide

After utilizing Ionic 3 to retrieve data from a WordPress API, I am encountering an issue with displaying the content on the app UI. The problem arises from the presence of HTML tags within the content being printed along with the text. While seeking solut ...

Transform PHP array into a JavaScript array

Currently, I am using Laravel and retrieving a list of values from a database with the following code: $idordenes = DB::table('ordenes')->select('id')->get(); Upon echoing the idordenes variable, the output is as follows: [{"fa ...