Importing node module what exports default class results in a 'module' not a 'constructor'

老子叫甜甜 提交于 2019-12-24 07:34:15

问题


I am trying to import a node module React-Signature-Pad. The index.js file looks like this:

import PropTypes from 'prop-types'
import React, { Component } from 'react'
import trimCanvas from 'trim-canvas'

import Bezier from './bezier.js'
import Point from './point.js'

export default class SignatureCanvas extends Component {
  static propTypes = {
    velocityFilterWeight: PropTypes.number,
    minWidth: PropTypes.number,
    maxWidth: PropTypes.number,
    dotSize: PropTypes.oneOfType([PropTypes.number, PropTypes.func]),
    penColor: PropTypes.string,
    onEnd: PropTypes.func,
    onBegin: PropTypes.func,
    canvasProps: PropTypes.object
  }

  static defaultProps = {
    velocityFilterWeight: 0.7,
    minWidth: 0.5,
    maxWidth: 2.5,
    dotSize: () => {
      return (this.props.minWidth + this.props.maxWidth) / 2
    },
    penColor: 'black',
    backgroundColor: 'rgba(0,0,0,0)',
    onEnd: () => {},
    onBegin: () => {}
  }

  componentDidMount () {
    this._ctx = this._canvas.getContext("2d");
    //.....

I am trying to use it like this: import * as SignatureCanvas from 'react-signature-canvas'

However then SignatureCanvas evaulates to an object with a single property of 'default'. So when I use I get an error because SignatureCanvas is not actually a constructor.

The only way I have been able to get this to work is to import it like this:

declare var require: any;
var SignatureCanvas = require('react-signature-canvas').default;

Which doesn't seem right. Which is the proper way to import?

I am using WebPack2 to bundler the site if it matters.


回答1:


You will have to import it like as the module has a default exported member:

import SignatureCanvas from 'react-signature-canvas'

A default export is simply a named export with the name default. So you can even do this:

import { default as SignatureCanvas } from 'react-signature-canvas'

Or:

import * as SignatureCanvas from 'react-signature-canvas'

//... and use the `SignatureCanvas` class by accessing the `default property`
new SignatureCanvas.default()

See documentation on default exports: https://www.typescriptlang.org/docs/handbook/modules.html#default-exports




回答2:


The way to import this module - and have it working as a class - is:

import SignatureCanvas from 'react-signature-canvas';

var x = new SignatureCanvas(...);

The import * as xxx from 'xxx' syntax works exactly as you found out: the default exported artifact of the module xxx is set as xxx.default. In your case you would have to do:

import * as SignatureCanvas from 'react-signature-canvas';

var x = new SignatureCanvas.default(...); // now x is the same as above


来源:https://stackoverflow.com/questions/44247758/importing-node-module-what-exports-default-class-results-in-a-module-not-a-co

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!