首页 > 解决方案 > 使用 Webpack 加载 Jquery

问题描述

我已经编写了一个 npm 包(调用它ABC),我正在一个 create react 应用程序中对其进行测试。这个包使用 Webpack。我的包还依赖于另一个DEF依赖于 Jquery 的包(称为它)。当我加载我的 create react 应用程序时,我看到了这个错误:

DEF.min.js:1 Uncaught TypeError: n.$ is not a function

我怀疑这意味着我的webpack.config.js文件配置不正确。

//webpack.config.js

const webpack = require("webpack");
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
  externals: {
    jquery: 'jQuery',
    $: 'jQuery'
  },
  entry: {
    bundle: "./app/index.js"
  },
  output: {
    path: path.join(__dirname, "dist"),
    // [name] interpolates an entry point name (bundle, vendor, etc)
    // [chunkhash] interpolates cache busting hash
    filename: "[name].[chunkhash].js"
  },
  module: {
    rules: [    
      // {
      //   test: require.resolve('jquery'),
      //   use: [{
      //     loader: 'expose-loader',
      //     options: 'jQuery'
      //   },{
      //     loader: 'expose-loader',
      //     options: '$'
      //   }]
      // },
  {
    use: "babel-loader",
    test: /\.js$/,
    exclude: /node_modules/
  },
  {
    use: ["file-loader"],
    test: /\.(png|jpg|gif|svg)$/
  },
  {
    use: ["url-loader"],
    test: /\.(eot|svg|ttf|woff|woff2)$/
  }
]


},
  plugins: [
    new webpack.ProvidePlugin({
      $: "jquery",
      "$": "jquery",
      "jQuery": "jquery",
      "jquery": "jquery",
      jQuery: "jquery",
      jquery: "jquery",
      "window.jQuery": "jquery",
      "window.$": "jquery"
  }),
    new webpack.optimize.CommonsChunkPlugin({
      names: ["manifest"]
    }),
    // This plugin automatically injects scripts into the
    // head of index.html so we don't have to manually
    // manage them.
    new HtmlWebpackPlugin({
      template: "app/index.html"
    }),

    new webpack.DefinePlugin({
      "process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV)
    })
  ],
  devtool: 'source-map',
  // webpack-dev-server configuration
  devServer: {

    host: "0.0.0.0",
    port: 9000,

    public: "localhost",
    watchOptions: {
      ignored: /node_modules/
    }
  }

};

我曾尝试使用 jquery 官方 Webpack 文档中的示例,但没有运气:

https://webpack.js.org/configuration/externals/#externals https://webpack.js.org/loaders/expose-loader/#examples

标签: jquerynode.jsreactjsnpmwebpack

解决方案


我来用一个简单的解决方案来解决我自己的问题。当我在包DEF中的 javascript 文件中使用包时ABC,我通过如下import语句将其包含在内import 'DEF';:只需将其更改为require ('DEF');就是解决方案。目前,我正在调查为什么这会产生重大影响。应该注意的是,我不需要配置我ABC的 webpack 配置来处理 javascript,因此我已经删除了负责 jQuery 的 providerPlugin 和 externals 对象。

这有助于解释为什么会这样。


推荐阅读