如何在 Webpack 中使用 p5js [英] How to use p5js with Webpack

查看:74
本文介绍了如何在 Webpack 中使用 p5js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个基于 p5js 的库,所以在我的 Javascript 项目中我有Webpack 作为开发依赖项安装,我在 start.js 中编写:

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 :(

然而,在 p5 中没有找到任何引用.我期待找到对 p5 函数的引用,例如 rectellipsesetup,但什么也没有.

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.

我的 Webpack 配置文件是:

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']
                    }
                }
            }
        ],  
    }
};

我做错了什么?

推荐答案

就像iluvAS说的,你需要使用实例模式.

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>

这是另一个在 stackblitz 上托管 webpack 和 es6 模块导入的工作示例(在后台使用 webpack):https://stackblitz.com/edit/p5-in-webpack

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

这篇关于如何在 Webpack 中使用 p5js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆