我已经编写了一个npm包(称为ABC),并正在create react应用程序中对其进行测试。该软件包使用Webpack。我的软件包还依赖于另一个DEF依赖于Jquery的软件包(称为)。加载我的create react应用程序时,我看到此错误:
ABC
DEF
DEF.min.js:1 Uncaught TypeError: n.$ is not a function
我怀疑这意味着我的webpack.config.js文件配置不正确。
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/ } } };
我曾尝试使用官方Webpack文档中的jquery实例,但没有运气:
https://webpack.js.org/configuration/externals/#externals https://webpack.js.org/loaders/expose- loader/#examples
我来了一个简单的解决方案来解决自己的问题。当我在包中的DEFjavascript文件中使用包时ABC,我通过如下import语句将其包括在内:import 'DEF';。只需将其更改require ('DEF');为解决方案即可。目前,我正在调查为什么这会有所不同。应该注意的是,我不需要配置我ABC的webpack配置来处理javascript,因此此后我删除了占jQuery的providerPlugin和externals对象。
import
import 'DEF';
require ('DEF');
这有助于解释为什么是这种情况。