mattdesl / canvas-sketch

[beta] A framework for making generative artwork in JavaScript and the browser.
MIT License
5.01k stars 393 forks source link

Error running canvas-sketch-cli with d3 #149

Open superkelvint opened 2 years ago

superkelvint commented 2 years ago

I'm getting this error with a sketch that uses d3.js (v7):

ParseError: 'import' and 'export' may appear only with 'sourceType: module'

Here's a minimal example based on canvas-sketch-cli --new template:

import {scaleLinear, scaleSequential, scaleSequentialLog} from "d3-scale";
import canvasSketch from 'canvas-sketch';

const settings = {
  dimensions: [ 2048, 2048 ]
};

const sketch = () => {
  return ({ context, width, height }) => {
    context.fillStyle = 'white';
    context.fillRect(0, 0, width, height);
  };
};

canvasSketch(sketch, settings);
L-A commented 2 years ago

Some context on this, because the issue will slowly become more prevalent as more packages start to publish with ESM syntax:

The message actually stems from canvas-sketch-cli, which itself uses esmify. The current configuration supports the import/export syntax only in files you're writing within your project – external dependencies, like those installed in node_modules, will not compile with the current settings.

If you want to enable support for import/export throughout the dependency tree, here's how to do so. I'm assuming you've followed the docs and installed canvas-sketch-cli globally:

First, get the location of your global node_modules folder:

npm root -g

Then you can open or navigate to this location, and find the canvas-sketch-cli folder. In it, go to src/index.js. You are looking to modify this line:

https://github.com/mattdesl/canvas-sketch-cli/blob/75137f126db145ce3a835e092e29ffc93e2eb8f2/src/index.js#L595

Change nodeModules to true to allow emsify to parse all installed dependencies. Keep in mind that this will make your initial start slower. You're also patching something that risks getting overwritten if you reinstall your global dependencies.


@mattdesl I'm not certain how I'd go about updating canvas-sketch-cli to alleviate this issue other than the aforementioned "fix" (or downright replacing esmify with a different plugin), but I'd be happy to take on that chore if you have a preferred solution in mind.

mattdesl commented 2 years ago

I think ideally we should remove the budo + browserify + babel + esmify packages and use another bundler and esm solution. I really would like to support the following:

There are a few tools coming out recently but still looks like esbuild is my favourite and should work with all of the above. But it's a huge overhaul...