【问题标题】:TypeError of select2 with Webpack使用 Webpack 的 select2 的 TypeError
【发布时间】:2016-10-24 22:52:15
【问题描述】:

我已经通过 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"}
},
}

【问题讨论】:

  • 分享你的 webpack.config 文件
  • @JaganathanBantheswaran 我刚刚分享了上面的 webpack.config 文件。请建议。谢谢!

标签: javascript webpack jquery-select2 typeerror


【解决方案1】:

更新 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,
})]

【讨论】:

  • 嘿@JaganathanBantheswaran,谢谢你的建议!我试了一下,但我没有运气。我终于通过在 webpack.config.js 的 externals 部分配置 jquery 解决了这个问题。
  • 很好,你解决了这个问题。这是我们解决 jQuery 问题的方法之一。
猜你喜欢
  • 1970-01-01
  • 2019-10-21
  • 1970-01-01
  • 2016-11-23
  • 2019-11-14
  • 2017-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多