我想编写一个基于 p5js 的库,因此在我的 Javascript 项目中,我将 Webpack 安装为开发依赖项,并将其写在
start.js
:
import p5 from "p5";
p5.ellipse(0, 0, 100, 100); // Function not found :(
但是,
p5
中没有找到任何参考资料。我本来希望找到对 p5 函数的引用,例如 rect
或 ellipse
或 setup
,但什么也没有。
我的 Webpack 配置文件是:
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所说,你需要使用实例模式。
// 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
这是一个完整的、可运行的 P5 + Webpack 启动器,以补充 这个答案,它正确地建议使用 p5 的实例模式。
package.json:
{
"dependencies": {
"p5": "^1.9.3"
},
"devDependencies": {
"html-webpack-plugin": "^5.6.0",
"webpack": "^5.91.0",
"webpack-cli": "^5.1.4",
"webpack-dev-server": "^5.0.4"
}
}
webpack.config.js:
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
mode: "development",
entry: {
main: path.resolve("src", "index.js"),
},
output: {
filename: "index.js",
path: path.resolve("dist"),
},
plugins: [
new HtmlWebpackPlugin({
template: path.resolve("public", "index.html"),
}),
],
};
public/index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Webpack + P5</title>
</head>
<body>
</body>
</html>
src/index.js:
import p5 from "p5";
new p5(p => {
p.frameRate(2);
p.draw = () => {
p.print(p.frameCount);
};
});
安装并运行:
$ npm i
$ npx webpack serve
导航到 http://localhost:8080 并打开控制台以查看日志。