jquery - 使用 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
解决方案
我来用一个简单的解决方案来解决我自己的问题。当我在包DEF
中的 javascript 文件中使用包时ABC
,我通过如下import
语句将其包含在内import 'DEF';
:只需将其更改为require ('DEF');
就是解决方案。目前,我正在调查为什么这会产生重大影响。应该注意的是,我不需要配置我ABC
的 webpack 配置来处理 javascript,因此我已经删除了负责 jQuery 的 providerPlugin 和 externals 对象。
推荐阅读
- ios - TouchableWithoutFeedback 会中断 ScrollView。如何在不将视图放入 ScrollView 的情况下进行修复?
- angular - Angular Datables 固定标头
- swift - 无法使用“String”类型的索引为“[Any]”类型的值下标
- awk - 合并特定列中的前两行
- pseudocode - 程序的时间复杂度
- python - 使用数据生成更漂亮的图
- python - NCHW和NHWC网络格式转换Tensorflow模型
- javascript - React Table:如何对每个holeOne 到holeNine 求和(求和)值,并将总和显示为out:41 中的值?
- android - Flutter:“使用静态访问无法访问实例成员'playing'。”
- typescript - 无法理解这些泛型(?)定义中发生了什么,包括。类型参数列表