首页 > 解决方案 > Typescript + select2 + browserify = TypeError: $(...).select2 不是函数

问题描述

我决定将我的一个项目前端迁移到 typescript + browserify(来学习这些东西),一切都很顺利,直到我遇到“TypeError:$(...).select2 is not a function”......在浪费了很多之后数小时的谷歌搜索和测试不同的方法、导入等,但没有任何结果……现在是时候访问 stackoverflow.com 了 :)

我的设置是:

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

tsconfig.json

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

包.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"
  }
}

索引.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 的东西......

标签: javascripttypescriptjquery-select2browserify

解决方案


推荐阅读