Search code examples
javascripttypescriptqwik

Is this a problem with the Code Optimizer in the Qwik.js framework?


I'm getting an error that ChatGPT definitely thinks is coming from the code optimizer of Qwik.js, and if that's the case there's unfortunately nothing I can do to debug the issue.

const drawImageTask = useVisibleTask$(() => {
    const canvas = canvasSignal.value;
    if (canvas) {
      const ctx = canvas.getContext('2d');
      const img = new Image();
      img.src = mapProps.imageUrl;
      img.onload = async () => {
        const canvasSize = calculateCanvasSize(img); // < ------------------------- causes error

function calculateCanvasSize(image: HTMLImageElement) {
    const aspectRatio = image.width / image.height;
    const canvasWidth = window.innerWidth;
    const canvasHeight = canvasWidth / aspectRatio;
    return [canvasWidth, canvasHeight];
  }

12:02:14 AM [vite] Internal server error: Cannot read properties of null (reading '0') Plugin: vite-plugin-qwik File: G:/projects/websites/LoreCoords/Qwik Basic Template/src/components/map/map.tsx at createRollupError2 (G:\projects\websites\LoreCoords\Qwik Basic Template\[email protected]\qwik\optimizer.cjs:1624:38) at G:\projects\websites\LoreCoords\Qwik Basic Template\[email protected]\qwik\optimizer.cjs:2166:49 at Array.forEach () at G:\projects\websites\LoreCoords\Qwik Basic Template\[email protected]\qwik\optimizer.cjs:2164:23 at Object.transform (G:\projects\websites\LoreCoords\Qwik Basic Template\[email protected]\qwik\optimizer.cjs:1314:9) at TransformContext.transform (G:\projects\websites\LoreCoords\Qwik Basic Template\[email protected]\qwik\optimizer.cjs:2204:27) at Object.transform (file:///G:/projects/websites/LoreCoords/Qwik%20Basic%20Template/node_modules/vite/dist/node/chunks/dep-79892de8.js:43387:44) at async loadAndTransform (file:///G:/projects/websites/LoreCoords/Qwik%20Basic%20Template/node_modules/vite/dist/node/chunks/dep-79892de8.js:41105:29)


Solution

  • the issue was down to the fact that these methods were part of a component. The function definition was incorrect for calculateCanvasSize. Instead it should have been:

    const calculateCanvasSize = $((image: HTMLImageElement) => {  
        console.log(image.width + "= width" + image.height + "= image.height");    
         const aspectRatio = image.width / image.height;
         const canvasWidth = window.innerWidth;
         const canvasHeight = canvasWidth / aspectRatio;
         
        return [canvasWidth, canvasHeight];
        
      });