typescript中引用better-scroll

typescript中引用better-scroll,代码如下

import * as BScroll from 'better-scroll'
...
console.log(BScroll)
new BScroll('.wrapper')
...

控制台输出

{default: ƒ, __esModule: true}
> default:ƒ BScroll(el, options)
  __esModule:true
> __proto__:Object

> Uncaught TypeError: BScroll is not a constructor
...

检查作者package.jsontypes声明没问题

...
  "types": "./types/index.d.ts",
...

检查作者*.d.ts没问题

...
declare const BScroll: BScrollStatic;

declare module 'better-scroll' {
  export = BScroll;
}
...

求助,我这里是哪里错误了?

阅读 5k
4 个回答

问题在于这句话 new BScroll('.wrapper'),
错误很明显了,BScroll 不是一个构造器函数, 所以你不能使用new运算符。
你应该可以直接这么用吧BScroll('.wrapper').

import * as BScroll from 'better-scroll'
new BScroll.BScroll();
import  BScroll from 'better-scroll'
new BScroll();
新手上路,请多包涵

你的问题解决了吗? 我也遇到了同样的问题!

应该是打包的方式不对吧,你可能选的打包方式是 cmd,改成 iife 或者 umd 试一下
我是这样用的

 import * as BScroll from 'better-scroll'

 const styleScroll = new (<any>BScroll)(styleContainer)

@types/better-scroll 好像不是作者写的,所以好像有问题

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题