Home > database >  Typescript and nextjs: SyntaxError: Unexpected token 'export'
Typescript and nextjs: SyntaxError: Unexpected token 'export'

Time:06-26

I'm trying to develop online board app(project for portfolio) with react, nextjs, typescript. (using typescript for the first time)

So I have problem with importing roughjs into canvas.tsx .

Here is 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="relative flex h-full w-full"
        ></canvas>
    )
}

export default Canvas

In browser I have SyntaxError: Unexpected token 'export'.

And VS code also giving me this error in 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/[email protected]/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 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"
    }
}

Please help me, I tried all I could find on the Internet, nothing helped.

What I tried:

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

Getting Unexpected Token Export

here is github code of this project:

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

CodePudding user response:

The module is not bundled with type declarations. In this case you can switch to commonjs require syntax and it should work:

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

Also, you are not writing anything to your rough canvas. To write you can do something like that:

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