【发布时间】:2018-12-05 11:12:57
【问题描述】:
我已经编写了一个 npm 包(称为 ABC),我正在一个 create react 应用程序中对其进行测试。这个包使用 Webpack。我的包还依赖于另一个依赖于 Jquery 的包(称为DEF)。当我加载我的 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
【问题讨论】:
-
您正在构建的是一个将在其他地方使用的库?
-
我创建了一个我称之为
ABC的包,它需要一个包DEF,而这个DEF包使用了jQuery。为了测试我的ABC包是否正常工作,我在准系统创建反应应用程序中使用它。 -
ABC 是否安装了 jquery?我之所以这么问是因为,在 webpack 中使用 external 表示您将在其他地方使用 jquery,而不是在这个捆绑包中。
-
是的,
ABC已安装 jquery。它位于其package.json文件中,因此已安装。
标签: jquery node.js reactjs npm webpack