1

I am having trouble getting this package to work. I have made a basic P5JS project and I cannot get the import to work in my JS file.

This is my JS file which works fine in the browser until I add the import line at the top.

import { createNoise2D } from "simplex-noise";

function setup() {
createCanvas(400, 400);
noLoop();
}

function draw() {
background(220);
}

I fixed the initial errors by adding the "type" : "module", line to my package.json and added type="module" to my html script tag for the JS file. This is the error I am left with

Failed to resolve module specifier "simplex-noise". Relative references must start with either "/", "./", or "../".

Any ideas? I'm completely lost

1
  • Please share a minimal reproducible example including your package.json. What bundler are you using, if any? Or are you trying to run this via CDN and use a browser module rather than a Node build? Commented Apr 24, 2024 at 16:25

1 Answer 1

1

Here's a quick browser sketch for starters.

<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.9.3/p5.js"></script>
<script type="module">
import {createNoise2D} from "https://unpkg.com/[email protected]/dist/esm/simplex-noise.js";

const noise2d = createNoise2D();

new p5(p => {
  p.frameRate(2);

  p.draw = () => {
    p.print(noise2d(p.frameCount, p.frameCount));
  };
});
</script>

The Node approach depends a bit on the build setup you have. Make sure to install the package with npm i simplex-noise if the import is failing.

Here's a simple, complete Parcel setup you can work off of:

src/index.js:

import p5 from "p5";
import {createNoise2D} from "simplex-noise";

const noise2d = createNoise2D();

new p5(p => {
  p.frameRate(2);

  p.draw = () => {
    p.print(noise2d(p.frameCount, p.frameCount));
  };
});

src/index.html:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8"/>
    <title>My First Parcel App</title>
    <script src="./index.js" type="module"></script>
  </head>
  <body>
  </body>
</html>

package.json:

{
  "dependencies": {
    "p5": "^1.9.3",
    "simplex-noise": "^4.0.1"
  },
  "devDependencies": {
    "parcel": "^2.12.0"
  }
}

Run:

$ npm i
$ npx parcel src/index.html
Server running at http://localhost:1234
✨ Built in 4ms

You should see the app at http://localhost:1234. Open the console to see the noise running.

The code for Webpack or Vite shouldn't be significantly different, if at all--just more config files.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.