首页 > 解决方案 > 未找到模块:错误:无法解析“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.js

const 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

为什么在尝试创建新对象时会失败,但在单独类型转换变量时工作正常?

标签: typescriptwebpackfabricjs

解决方案


我相信您输入Point错误。看起来打字将其作为主库文件上的命名导出。

这意味着您应该能够简单地执行以下操作:

import { fabric, Point } from 'fabric';

const point = new Point(1, 2) // Works

操场


或者可能:

const Point = fabric.Point
const point = new Point(1, 2)

推荐阅读