You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js+TS引入roughjs报Unexpected token 'export'错误求助

roughjs在Next.js+TypeScript项目中引入报错解决方案

你遇到的两个报错分属不同原因,按下面步骤逐一修复即可:

修复浏览器SyntaxError: Unexpected token 'export'报错

这个报错本质是Next.js 12默认不会转译node_modules内的ESM模块,你当前引入的roughjs/bundled/rough.esm是纯ESM格式文件,代码里的export语法没有被编译,浏览器直接运行就会抛错。

  • 第一步:替换引入路径,不要引esm的子路径包,直接引入主包:
    // 把原来的import rough from 'roughjs/bundled/rough.esm'换成下面这行
    import rough from 'roughjs'
    
  • 第二步:因为canvas是浏览器专属API,服务端渲染阶段不存在DOM对象,需要把Canvas组件设置为仅客户端渲染,在引用Canvas组件的页面/父组件里用动态导入:
    import dynamic from 'next/dynamic'
    const Canvas = dynamic(() => import('./Canvas'), { ssr: false })
    
  • 补充:你代码里的useLayoutEffect没有传依赖数组,会在组件每次重渲染时重复执行,记得加空数组作为第二个参数,保证逻辑只在组件挂载时执行一次:
    useLayoutEffect(() => {
      const canvas = document.getElementById('canvas') as HTMLCanvasElement      
      const ctx = canvas.getContext('2d')
      const roughCanvas = rough.canvas(canvas)
      // 这里补画布宽高适配、绘制逻辑
    }, []) // 加空依赖
    

修复TypeScript找不到模块声明的报错

roughjs本身没有内置TypeScript类型定义,也没有对应的官方@types类型包,手动补类型声明即可:

  1. 在项目根目录(和tsconfig.json同级)新建roughjs-env.d.ts文件,写入以下内容:
    declare module 'roughjs' {
      import { RoughCanvas, RoughGenerator } from 'roughjs/bin/core'
      export function canvas(canvas: HTMLCanvasElement): RoughCanvas
      export function generator(config?: any): RoughGenerator
      const rough: {
        canvas: typeof canvas
        generator: typeof generator
      }
      export default rough
    }
    
    declare module 'roughjs/bin/core' {
      export interface RoughCanvas {
        line: (x1: number, y1: number, x2: number, y2: number, options?: any) => void
        rectangle: (x: number, y: number, w: number, h: number, options?: any) => void
        circle: (x: number, y: number, diameter: number, options?: any) => void
        // 后续用到其他roughjs的绘制方法,在这里补充类型即可
      }
      export interface RoughGenerator {}
    }
    
  2. 打开tsconfig.json,把新建的声明文件加到include配置里:
    {
      "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "roughjs-env.d.ts"]
    }
    

如果只是临时跑通项目,也可以直接在项目默认的next-env.d.ts里加一行兜底声明,不过这种方式会丢失类型提示,不推荐长期使用:

declare module 'roughjs'

额外优化提示

你当前的canvas标签只通过CSS设置了宽高,没有设置标签原生的width、height属性,会导致绘制内容模糊,建议在useLayoutEffect里拿到canvas元素后,按设备像素比设置画布实际分辨率:

const dpr = window.devicePixelRatio || 1
canvas.width = canvas.clientWidth * dpr
canvas.height = canvas.clientHeight * dpr
ctx.scale(dpr, dpr)

内容的提问来源于stack exchange,提问作者Grayza

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 06:39:15