问题
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