angular想引用sortablejs这个拖拽插件,因为是第三方库,没有index.d.ts声明文件,在引入的过程中太过曲折。我会先把最后结果粘出来,然后再将曲折过程写出来,毕竟研究了这么半天。
画面
拖动后效果:
法一:
下载包
npm install sortablejs --save
app.component.html
<ul>
<ng-container *ngFor="let item of list">
<li>{{item}}</li>
</ng-container>
</ul>
app.component.ts
import { Component, AfterViewInit } from '@angular/core';
import Sortable from 'node_modules/sortablejs/Sortable.min.js';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent implements AfterViewInit {
list: string[] = ['2000001', '2000002', '2000003', '2000004', '2000005', '2000006', '2000007'];
ngAfterViewInit() {
const el = document.querySelector('ul');
const sortable = Sortable.create(el, {});
}
}
法二:
下载包
npm install sortablejs --save
npm install --save @types/sortablejs
app.component.ts
import { Component, AfterViewInit } from '@angular/core';
import Sortable from 'sortablejs/Sortable';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent implements AfterViewInit {
list: string[] = ['2000001', '2000002', '2000003', '2000004', '2000005', '2000006', '2000007'];
ngAfterViewInit() {
const el = document.querySelector('ul');
const sortable = Sortable.create(el, {});
}
}
曲折过程
问题1:用下面方式引用Sortable
import { Sortable } from 'node_modules/sortablejs/Sortable.min.js';
画面报错1:
Cannot read property 'create' of undefined
解决1:Sortable.create(el, {}); 换成 new Sortable(el, {});
画面报错2:node_modules_sortablejs_Sortable_min_js__WEBPACK_IMPORTED_MODULE_2__.Sortable is not a constructor
前面错误不用看,看最后Sortable is not a constructor就可以,它的意思是Sortable不是个对象大概是这个意思
解决2:改成
import Sortable from 'node_modules/sortablejs/Sortable.min.js';
好使了,只是去了个大括号。当然改成下面写法也可以
import * as Sortable from 'node_modules/sortablejs/Sortable.min.js';
然后用 Sortable.create(el, {}); 也不报错了。
问题2:用@types这种声明方式
npm install --save @types/sortablejs
import { Sortable } from 'sortablejs';
报错1:模块“"../../node_modules/_@types_sortablejs@1.10.2@@types/sortablejs"”没有导出的成员“Sortable”。
解决1:改为 import { Sortable } from 'sortablejs/Sortable'; 这样就不会提示语法错误了再改一下
import Sortable from 'sortablejs/Sortable';
就不会出现画面错误了,神奇吧。