Webpack的select2类型错误

TypeError of select2 with Webpack

本文关键字:错误 类型 select2 Webpack      更新时间:2023-09-26

我已经通过Webpack成功地将select2.js的本地副本与几个*.js文件捆绑在一起。然而,它总是抛出TypeError,警告e.select2不是一个函数。有趣的是,如果我需要从CDN select2.js,它在初始页面加载时工作,但在刷新页面后抛出相同的错误。

这个错误在我绑定之前从未发生过。

谁能给点建议?谢谢!

根据请求,我在下面分享webpack.config.js。

var path = require("path");
var webpack = require('webpack');
var BundleTracker = require('webpack-bundle-tracker');
module.exports = {
context: __dirname,
entry: {
    annotation: './assets/js/annotation_index',
    subject: './assets/js/subject_index',
    highchart: './assets/js/highchart_index',
    protocol: './assets/js/protocol_index',
    subscription: './assets/js/subscription_index'
},
output: {
    path: path.resolve('./assets/bundles/'),
    filename: "[name].js",
},
externals: [
    require('webpack-require-http')
],
plugins: [
    new BundleTracker({filename: './webpack-stats.json'})
],
module: {
    loaders: [
        { test: /'.jsx?$/, exclude: /node_modules/, loader: 'babel-loader', query: {compact: false} }, // to transform JSX into JS
    ],
},
resolve: {
    modulesDirectories: ['node_modules', './assets/js/annotation'],
    extensions: ['', '.js', '.jsx'],
    alias: { jquery: "./jquery"}
},
}

更新1:由于OP使用脚本标签加载jQuery,所以更好的选择是使用外部选项来不捆绑jQuery。

externals: {
        "jquery": "jQuery"
    }

你可以尝试ProvidePluginCommonsChunkPlugin插件

entry: {
  vendor: ["jquery", "other lib1", 'other lib2'],
  ...
},
plugins: [
    new webpack.ProvidePlugin({
        $: "jquery",
        jQuery: "jquery"
    }),
    new CommonsChunkPlugin({
       name: "vendor",
       filename: "vendor.js"
       minChunks: Infinity,
})]
相关文章: