JSPM + TypeScript + PhotoSwipe:如何成功導入並使用這個庫?
我正在嘗試在我的 JSPM 和 TypeScript 項目中使用 PhotoSwipe 庫,但沒有成功(我現在快崩潰了..)。
使用來自 DefinitelyTyped 的 PhotoSwipe 修改版定義檔(原本的無法使用——出現「PhotoSwipe 未定義」),我想出了這個方案:
declare var PhotoSwipe: PhotoSwipe.IPhotoSwipeStatic;
declare var PhotoSwipeUI_Default: PhotoSwipeUI_Default.IPhotoSwipeUI_DefaultStatic;
declare module PhotoSwipe {
...
interface IPhotoSwipeStatic {
new <T extends Options> (pswpElement: HTMLElement,
uiConstructor: (new (pswp: PhotoSwipeInstance<T>, framework: UIFramework) => UI<T>) | boolean,
items: PhotoSwipe.Item[],
options: T): PhotoSwipeInstance<T>;
}
}
declare class PhotoSwipeInstance<T extends PhotoSwipe.Options> {
...
}
declare module PhotoSwipeUI_Default {
...
interface IPhotoSwipeUI_DefaultStatic {
new (pswp: PhotoSwipeInstance<Options>, framework: PhotoSwipe.UIFramework): PhotoSwipeUI_DefaultInstance;
}
}
declare class PhotoSwipeUI_DefaultInstance implements PhotoSwipe.UI<PhotoSwipeUI_Default.Options> {
...
}
嘗試匯入它時,我似乎無法弄清楚如何使用以下方式創建 PhotoSwipe 的實例:
const photoSwipe = new PhotoSwipe(pswpElement, PhotoSwipe.PhotoSwipeUI, items, options);1)
declare module "photoswipe" {
export = { PhotoSwipe, PhotoSwipeUI_Default };
}
並且 import "photoswipe"; => 我得到 ReferenceError: PhotoSwipe 未定義
2)
declare module "photoswipe" {
export var PhotoSwipe: PhotoSwipe.IPhotoSwipeStatic;
export var PhotoSwipeUI_Default: PhotoSwipeUI_Default.IPhotoSwipeUI_DefaultStatic;
}
並且 import { PhotoSwipe, PhotoSwipeUI_Default } from "photoswipe"; => 我得到 TypeError: photoswipe_1.PhotoSwipe 不是一個建構函數
有人嗎?
答案#1
我知道可能已經很晚了,但這裡有解決辦法:
require([
'path/to/photoswipe.js',
'path/to/photoswipe-ui-default.js'
], function( PhotoSwipe, PhotoSwipeUI_Default ) {
// var gallery = new PhotoSwipe( someElement, PhotoSwipeUI_Default ...
// gallery.init()
// ...
});
來源 - http://photoswipe.com/documentation/getting-started.html
另外別忘了在之前導入一些文件:
import 'photoswipe/dist/photoswipe.css';
import 'photoswipe/dist/default-skin/default-skin.css';
我正在嘗試用 TypeScript 的方式來做,使用全域類型,簡單地這樣:
import { PhotoSwipe, PhotoSwipeUI_Default } from 'photoswipe';
但它沒有用。我出現了和你一樣的錯誤。
祝你好運!
附註 - 對,我有用 webpack 測試過,但沒有用 JSPM 測試過。
答案#2
npm install photoswipe
npm install --save @types/photoswipe
從 npm 安裝 photoswipe 及其型別定義。
import photoSwipe from 'photoswipe'
然後你可以使用上述的匯入語句來使用它。
希望這會有幫助。
