# How do I import p5 via npm?

**URL:** <https://discourse.processing.org/t/how-do-i-import-p5-via-npm/11543>\
**Category:** Libraries\
**Created:** [May 24, 2019, 10:50am UTC](https://discourse.processing.org/t/how-do-i-import-p5-via-npm/11543 "2019-05-24T10:50:02Z")\
**Posts on this page:** 7\
**Page:** 1

<div class="post-metadata">

**Author:** ![lion9](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/lion9/32/5345_2.png) [@lion9](https://discourse.processing.org/u/lion9)\
**Post date:** [May 24, 2019, 10:50am UTC](https://discourse.processing.org/t/how-do-i-import-p5-via-npm/11543/1 "2019-05-24T10:50:02Z")

</div>

I have tried to import p5 into my project using webpack (you can see the code here [GitHub - lion9/p5-npm](https://github.com/lion9/p5-npm)), but to no avail. Everything seems to be built into the app.bundle.js file, but the canvas is not appering at all.

---

<div class="post-metadata">

**Author:** ![figraham](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/figraham/32/4161_2.png) [@figraham](https://discourse.processing.org/u/figraham)\
**Post date:** [May 26, 2019, 11:05pm UTC](https://discourse.processing.org/t/how-do-i-import-p5-via-npm/11543/2 "2019-05-26T23:05:02Z")

</div>

As far as I know the default global mode doesn’t work with `import p5 from 'p5';`. [Instance mode](https://github.com/processing/p5.js/wiki/Global-and-instance-mode) should work.

Here’s an example:

```auto
import p5 from 'p5';

const sketch = (s) => {
    s.setup = () => {
        s.createCanvas(10, 10);
    }

    s.draw = () => {
        s.background(0);
        s.circle(10, 10, 10);
    }
}

const sketchInstance = new p5(sketch);

```

Hope that helps!

---

<div class="post-metadata">

**Author:** ![noone](https://avatars.discourse-cdn.com/v4/letter/n/ecae2f/32.png) [@noone](https://discourse.processing.org/u/noone)\
**Post date:** [August 30, 2021, 7:43pm UTC](https://discourse.processing.org/t/how-do-i-import-p5-via-npm/11543/3 "2021-08-30T19:43:01Z")

</div>

Is there anyway to not write `s.` everywhere? Maybe I could import functions manually?

---

<div class="post-metadata">

**Author:** ![KumuPaul](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/kumupaul/32/13072_2.png) [@KumuPaul](https://discourse.processing.org/u/KumuPaul)\
**Post date:** [August 31, 2021, 8:24pm UTC](https://discourse.processing.org/t/how-do-i-import-p5-via-npm/11543/4 "2021-08-31T20:24:50Z")

</div>

Technically there is a way to temporarily introduce stuff into the global scope in JavaScript: the [`with` block](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/with).

```auto
import p5 from 'p5';

const sketch = (s) => {
    s.setup = () => {
        s.createCanvas(10, 10);
    }

    s.draw = () => {
        with (s) {
            background(0);
            circle(10, 10, 10);
        }
    }
}

const sketchInstance = new p5(sketch);

```

However, usage of the with block is generally discouraged because it can create confusion about what is being referenced.

---

<div class="post-metadata">

**Author:** ![KumuPaul](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/kumupaul/32/13072_2.png) [@KumuPaul](https://discourse.processing.org/u/KumuPaul)\
**Post date:** [August 31, 2021, 8:27pm UTC](https://discourse.processing.org/t/how-do-i-import-p5-via-npm/11543/5 "2021-08-31T20:27:04Z")

</div>

Technically you could also use a destructuring assignment for the stuff you intend to use:

```auto
import p5 from 'p5';

const sketch = (s) => {
    const { createCanvas, background, circle } = s;
    s.setup = () => {
        createCanvas(10, 10);
    }

    s.draw = () => {
        background(0);
        circle(10, 10, 10);
    }
}

const sketchInstance = new p5(sketch);

```

With the obvious downside of needing to list every p5.js function and constant you intend to use.

---

<div class="post-metadata">

**Author:** ![jeremydouglass](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/jeremydouglass/32/20_2.png) [@jeremydouglass](https://discourse.processing.org/u/jeremydouglass)\
**Post date:** [September 18, 2021, 8:46pm UTC](https://discourse.processing.org/t/how-do-i-import-p5-via-npm/11543/6 "2021-09-18T20:46:44Z")

</div>

@KumuPaul – the destructuring option looks interesting for automatic code conversion.

It seems like (perhaps) a conversion script could take the code of a global sketch as input and then produce a the code of an instance mode sketch as output, with a destructuring assignment that listed only the p5.js functions and constants that are actually called.

---

<div class="post-metadata">

**Author:** ![KumuPaul](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/kumupaul/32/13072_2.png) [@KumuPaul](https://discourse.processing.org/u/KumuPaul)\
**Post date:** [September 18, 2021, 8:53pm UTC](https://discourse.processing.org/t/how-do-i-import-p5-via-npm/11543/7 "2021-09-18T20:53:07Z")

</div>

Neat idea. It would require some JavaScript static analysis tool or library to determine which p5.js functions/constants/properties were actually used. But here’s a big destructuring assignment with everything as of 1.4.0:

```javascript
const { ADD, ALT, ARROW, AUDIO, AUTO, AXES, BACKSPACE, BASELINE, BEVEL, BEZIER, BLEND, BLUR, BOLD, BOLDITALIC, BOTTOM, BURN, CENTER, CHORD, CLAMP, CLOSE, CONTROL, CORNER, CORNERS, CROSS, CURVE, DARKEST, DEGREES, DEG_TO_RAD, DELETE, DIFFERENCE, DILATE, DODGE, DOWN_ARROW, ENTER, ERODE, ESCAPE, EXCLUSION, FALLBACK, FILL, GRAY, GRID, HALF_PI, HAND, HARD_LIGHT, HSB, HSL, IMAGE, IMMEDIATE, INVERT, ITALIC, LABEL, LANDSCAPE, LEFT, LEFT_ARROW, LIGHTEST, LINEAR, LINES, LINE_LOOP, LINE_STRIP, MIRROR, MITER, MOVE, MULTIPLY, NEAREST, NORMAL, OPAQUE, OPEN, OPTION, OVERLAY, P2D, PI, PIE, POINTS, PORTRAIT, POSTERIZE, PROJECT, QUADRATIC, QUADS, QUAD_STRIP, QUARTER_PI, RADIANS, RADIUS, RAD_TO_DEG, REMOVE, REPEAT, REPLACE, RETURN, RGB, RIGHT, RIGHT_ARROW, ROUND, SCREEN, SHIFT, SOFT_LIGHT, SQUARE, STROKE, SUBTRACT, TAB, TAU, TESS, TEXT, TEXTURE, THRESHOLD, TOP, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, TWO_PI, UP_ARROW, VIDEO, WAIT, WEBGL, accelerationX, accelerationY, accelerationZ, deltaTime, deviceOrientation, displayHeight, displayWidth, focused, frameCount, height, isKeyPressed, key, keyCode, keyIsPressed, mouseButton, mouseIsPressed, mouseX, mouseY, movedX, movedY, pAccelerationX, pAccelerationY, pAccelerationZ, pRotateDirectionX, pRotateDirectionY, pRotateDirectionZ, pRotationX, pRotationY, pRotationZ, pixels, pmouseX, pmouseY, pwinMouseX, pwinMouseY, rotationX, rotationY, rotationZ, touches, turnAxis, width, winMouseX, winMouseY, windowHeight, windowWidth, abs, acos, alpha, ambientLight, ambientMaterial, angleMode, append, applyMatrix, arc, arrayCopy, asin, atan, atan2, background, beginContour, beginShape, bezier, bezierDetail, bezierPoint, bezierTangent, bezierVertex, blend, blendMode, blue, boolean, box, brightness, byte, camera, ceil, char, circle, clear, clearStorage, color, colorMode, concat, cone, constrain, copy, cos, createA, createAudio, createButton, createCamera, createCanvas, createCapture, createCheckbox, createColorPicker, createDiv, createElement, createFileInput, createGraphics, createImage, createImg, createInput, createNumberDict, createP, createRadio, createSelect, createShader, createSlider, createSpan, createStringDict, createVector, createVideo, createWriter, cursor, curve, curveDetail, curvePoint, curveTangent, curveTightness, curveVertex, cylinder, day, debugMode, degrees, describe, describeElement, directionalLight, displayDensity, dist, downloadFile, ellipse, ellipseMode, ellipsoid, emissiveMaterial, endContour, endShape, erase, exitPointerLock, exp, fill, filter, float, floor, fract, frameRate, frustum, fullscreen, get, getFrameRate, getItem, getURL, getURLParams, getURLPath, green, gridOutput, hex, hour, httpDo, httpGet, httpPost, hue, image, imageMode, int, isLooping, join, keyIsDown, lerp, lerpColor, lightFalloff, lightness, lights, line, loadBytes, loadFont, loadImage, loadJSON, loadModel, loadPixels, loadShader, loadStrings, loadTable, loadXML, log, loop, mag, map, match, matchAll, max, millis, min, minute, model, month, nf, nfc, nfp, nfs, noCanvas, noCursor, noDebugMode, noErase, noFill, noLights, noLoop, noSmooth, noStroke, noTint, noise, noiseDetail, noiseSeed, norm, normal, normalMaterial, orbitControl, ortho, perspective, pixelDensity, plane, point, pointLight, pop, popMatrix, popStyle, pow, print, push, pushMatrix, pushStyle, quad, quadraticVertex, radians, random, randomGaussian, randomSeed, rect, rectMode, red, redraw, registerPromisePreload, removeElements, removeItem, requestPointerLock, resetMatrix, resetShader, resizeCanvas, reverse, rotate, rotateX, rotateY, rotateZ, round, saturation, save, saveCanvas, saveFrames, saveGif, saveJSON, saveJSONArray, saveJSONObject, saveStrings, saveTable, scale, second, select, selectAll, set, setAttributes, setCamera, setFrameRate, setMoveThreshold, setShakeThreshold, shader, shearX, shearY, shininess, shorten, shuffle, sin, smooth, sort, specularColor, specularMaterial, sphere, splice, split, splitTokens, spotLight, sq, sqrt, square, storeItem, str, stroke, strokeCap, strokeJoin, strokeWeight, subset, tan, text, textAlign, textAscent, textDescent, textFont, textLeading, textOutput, textSize, textStyle, textWidth, texture, textureMode, textureWrap, tint, torus, translate, triangle, trim, unchar, unhex, updatePixels, vertex, writeFile, year } = s;

```

so with that at the root of the instance mode function all you need to do is remove unused variables declared in that statement.
