How to use p5js with Webpack

南笙酒味 提交于 2020-12-06 12:14:59

问题


I want to write a library based on p5js, so in my Javascript project I have Webpack installed as dev-dependency and I write this in start.js:

import p5 from "p5";

p5.ellipse(0, 0, 100, 100); // Function not found :(

However, no references are found in p5. I was expecting to find references to p5's functions like rect or ellipse or setup, but nothing.

More info

My Webpack config file is:

const path = require('path');

module.exports = {
    entry: './start.js',
    output: {
        filename: 'start.js',
        path: path.resolve(__dirname, 'out')
    },
    module: {
        rules: [
            /* In order to transpile ES6 */
            {
                test: /\.js$/,
                exclude: /(node_modules|bower_components)/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: ['env']
                    }
                }
            }
        ],  
    }
};

What am I doing wrong?


回答1:


Like iluvAS said, you need to use instance mode.

// use this import in your webpack. Commented out because the CDN script exposes p5 as global
// import p5 from 'p5'; 

const containerElement = document.getElementById('p5-container');

const sketch = (p) => {
  let x = 100;
  let y = 100;

  p.setup = function() {
    p.createCanvas(800, 400);
  };

  p.draw = function() {
    p.background(0);
    p.fill(255);
    p.rect(x, y, 50, 50);
  };
};

new p5(sketch, containerElement);
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.js"></script>
<div id="p5-container"></div>

Here is another working example with webpack and es6 module imports hosted on stackblitz (which uses webpack under the hood): https://stackblitz.com/edit/p5-in-webpack



来源:https://stackoverflow.com/questions/50536543/how-to-use-p5js-with-webpack

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!