我正在尝试编写使用 HTML Canvas 的共享代码(在服务器和客户端上运行)。
在客户端上,这应该工作得很好。在服务器上,Node没有 Canvas (或DOM),所以我想使用node-canvas插件:https://github.com/Automattic/node-canvas .
但是,我无法找到一种访问它的方法,该方法不会使 webpack 尝试将 node-canvas 捆绑到我的客户端代码中(这会导致 webpack 崩溃)。有没有什么方法可以加载 Node Canvas ,让我可以使用在浏览器中使用的相同代码来引用它,而不会让 webpack 严重崩溃?
<小时/>我目前的努力没有奏效:
canvas.server.js
import Canvas from 'canvas';
const createCanvas = (width, height) => new Canvas(width, height);
export default createCanvas;
canvas.client.js
const createCanvas = (width, height) => {
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
return canvas;
};
export default createCanvas;
canvas.js
let createCanvas;
if (typeof document === 'undefined') {
// SERVER/node
createCanvas = require('./canvas.server.js');
} else {
// BROWSER
createCanvas = require('./canvas.client.js');
}
export default createCanvas;
使用中:
import createCanvas from './canvas';
const canvasElement = createCanvas(width, height);
const ctx = canvasElement.getContext('2d');
不幸的是,webpack 仍然捆绑在 node-canvas 中。
最佳答案
您是否尝试仅需要 node-canvas
when the code is running in node ?
如果你没有在前端代码中实际调用 require,webpack 不会对其进行捆绑。这意味着在上述条件语句中调用实际的 require
,而不是在文件顶部。这个很重要。另外,请验证您没有将 node-canvas
作为 webpack 中的入口点。
示例:
// let's assume there is `isNode` variable as described in linked answer
let canvas;
if (isNode) {
const Canvas = require('canvas');
canvas = new Canvas(x, y);
else {
canvas = document.getElementById('canvas');
}
// get canvas context and draw on it
在OP提供的代码示例后编辑:
我在 this WebpackBin 中重现了确切的结构证明这应该像上面解释的那样工作。毕竟,这是 common.js (和其他模块加载器)的一个功能,因此在 webpack 中受到支持。
我对代码的更改:
- 用该行调用的
console.log
替换了canvas.client.js
和canvas.server.js
中的代码 - 修复了
require
与export default
的错误使用(应为require(...).default
)。无关紧要,但必须这样做才能使代码正常工作。 - 删除了
canvasElement.getContex
调用。在示例代码中不起作用,并且无论如何都是无关的,因此没有必要 mock 它。
关于node.js - 在服务器和客户端上的共享代码中呈现 Canvas 界面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43815172/