Typescript + select2 + browserify = TypeError:$(...)。select2不是函数

时间:2018-07-04 03:10:11

标签: javascript typescript jquery-select2 browserify

我决定将我的一个项目前端迁移到Typescript + browserify(以学习这些东西),直到我遇到“ TypeError:$(...)。select2不是函数”为止,一切都进行得很顺利。经过大量浪费时间的谷歌搜索和测试differend方法,导入等,没有任何结果...是时候该访问stackoverflow.com了:)

我的设置是:

(您可以从这里https://github.com/Salamek/ts-select2克隆所有这些作为测试项目)

tsconfig.json

{
    "compilerOptions": {
        "allowJs": true,
        "target": "es5",
        "module": "commonjs",
        "moduleResolution": "node",
        "sourceMap": true
    },
    "include": [
        "./ts/**/*"
    ]
}

package.json

{
  "dependencies": {
    "jquery": "^3.3.1",
    "select2": "^4.0.5"
  },
  "devDependencies": {
    "@types/jquery": "^3.3.4",
    "@types/select2": "^4.0.47",
    "browserify": "^16.2.2",
    "del": "^3.0.0",
    "errorify": "^0.3.1",
    "gulp": "^4.0.0",
    "tsify": "^4.0.0",
    "typescript": "^2.9.2",
    "vinyl-source-stream": "^2.0.0",
    "watchify": "^3.11.0"
  }
}

index.html

<html>
  <head>
  </head>
  <body>
    <select class="select2">
      <option>Foo</option>
    </select>
  <script src="js/bundle.js" type="text/javascript"></script>
  </body>
</html>

gulpfile.js

const gulp = require('gulp');
const browserify = require('browserify');
const watchify = require('watchify');
const errorify = require('errorify');
const del = require('del');
const tsify = require('tsify');
const source = require('vinyl-source-stream');
//const runSequence = require('run-sequence');

function createBrowserifier(entry) {
    return browserify({
        basedir: '.',
        debug: true,
        entries: [entry],
        cache: {},
        packageCache: {}
    })
    .plugin(tsify)
    .plugin(watchify)
    .plugin(errorify);
}

function bundle(browserifier, bundleName, destination) {
    return browserifier
        .bundle()
        .pipe(source(bundleName))
        .pipe(gulp.dest(destination));
}

gulp.task('clean', () => {
    return del('./js/**/*')
});

gulp.task('tsc-browserify-src', () => {
    return bundle(
        createBrowserifier('./ts/main.ts'),
        'bundle.js',
        'js');
});

gulp.task('watch', () => {
    console.log('Watching...')
    gulp.watch(['ts/**/*.ts'], gulp.series('clean', 'tsc-browserify-src', 'watch'));
});

gulp.task('default', gulp.series('clean', 'tsc-browserify-src', 'watch'));

ts / main.ts

import * as $ from "jquery";
declare var global: any;
global.jQuery = $;
global.$ = $;

import "select2";

$(function () {
    $('.select2').select2();
});

成功完成gulp tsc-browserify-src任务后,没有出现任何错误,我得到了:

Uncaught TypeError: $(...).select2 is not a function
    at HTMLDocument.<anonymous> (main.ts:10)
    at mightThrow (jquery.js:3534)
    at process (jquery.js:3602)

在浏览器中打开index.html时。

谁知道该怎么办?我做错了什么? (直到昨天我一直在使用普通的jQuery,所以请慢慢对我:-))

PS:我的计划是完全切换到angular.js来处理前端内容,并完全放弃jQuery,但是现在我需要让我的应用使用原始组件并将应用代码重写为打字稿,然后慢慢删除jQuery内容...

0 个答案:

没有答案