typescript - 模块未找到:错误:无法解析 'fabric/fabric-impl'
我有以下文件
import {fabric} from 'fabric';
import {Point} from 'fabric/fabric-impl';
class Editor {
private canvas: fabric.Canvas;
private startPoint:Point;
constructor() {
let editor = document.getElementById('editor');
let canvasElement = document.createElement('canvas') as HTMLCanvasElement;
canvasElement.id = 'canvas';
editor.appendChild(canvasElement);
this.canvas = new fabric.Canvas('canvas');
this.canvas.on('mouse:down', (event) => {
this.startPoint = event.pointer;
console.log(event.pointer);
})
}
}
window.addEventListener('load', function(){
new Editor();
});
这可以正常编译,但是如果我想用类似的方式创建一个 new Point()
import {fabric} from 'fabric';
import {Point} from 'fabric/fabric-impl';
class Editor {
private canvas: fabric.Canvas;
private startPoint:Point;
constructor() {
let p = new Point(0,0);
let editor = document.getElementById('editor');
let canvasElement = document.createElement('canvas') as HTMLCanvasElement;
canvasElement.id = 'canvas';
editor.appendChild(canvasElement);
this.canvas = new fabric.Canvas('canvas');
this.canvas.on('mouse:down', (event) => {
this.startPoint = event.pointer;
console.log(event.pointer);
})
}
}
window.addEventListener('load', function(){
new Editor();
});
我在加载模块时出错
ERROR in ./resources/ts/Editor.ts
Module not found: Error: Can't resolve 'fabric/fabric-impl' in '/mnt/c/Users/Chris/code/test/resources/ts'
@ ./resources/ts/Editor.ts 2:0-43 5:20-25
这是我的节点包
package.json{
"private": true,
"devDependencies": {
"@types/fabric": "^3.6.8",
"fabric": "^3.6.3",
"ts-loader": "^8.0.1",
"typescript": "^3.9.6",
"webpack": "^4.43.0",
"webpack-cli": "^3.3.12"
},
"dependencies": {}
}
tsconfig.json// tsconfig.json
{
"compilerOptions": {
"incremental": true,
"target": "ES6",
"module": "es6",
"outDir": "./public/js/"
},
"files": [
"resources/ts/Editor.ts"
]
}
webpack.config.jsconst path = require('path');
module.exports = {
entry: './resources/ts/Editor.ts',
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/,
},
],
},
resolve: {
extensions: [ '.tsx', '.ts', '.js' ],
},
output: {
filename: 'Editor.js',
path: path.resolve(__dirname, 'public/js'),
},
};
运行 npx webpack --watch --mode=development
为什么在尝试创建新对象时会失败,但单独对变量进行类型转换时却能正常工作?
答案#1
我认为你导入 Point 的方式是错误的。看起来类型定义把它作为主库文件中的命名导出。
这意味着你应该能够简单地做:
import { fabric, Point } from 'fabric';
const point = new Point(1, 2) // Works
操场
或者可能是:
const Point = fabric.Point
const point = new Point(1, 2)
