macaoidh
macaoidh

Reputation: 23

Cannot get npm simplex-noise package import to work in JS project

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

Upvotes: 1

Views: 404

Answers (1)

ggorlen
ggorlen

Reputation: 57195

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.

Upvotes: 1

Related Questions