我在react中由于要使用jQuery的插件,因此使用npm install jquery --save的方式,在模块中引入了jquery,在开发环境中使用是没有问题的。但是现在npm run build后,打开打包后的index.html文件,页面会报:jQuery is not defind的错误。请教各位,这可能是什么原因呢?1.
1.webpack中也已经定义好了jquery的全局变量。
2.webpack版本为1.x
webpack代码:
//开发环境配置
var path = require('path')
var webpack = require('webpack')
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var OpenBrowserPlugin = require('open-browser-webpack-plugin');
// var nodeModulesPath = path.resolve(__dirname, 'node_modules')
// console.log(process.env.NODE_ENV)
module.exports = {
entry: path.resolve(__dirname, 'app/index.jsx'),
output: {
path: __dirname + "/build",
filename: "bundle.js"
},
resolve:{
extensions:['', '.js','.jsx'],
alias: {
handsontable: path.resolve(__dirname, 'node_modules/handsontable-pro')
}
},
module: {
// preLoaders: [
// // 报错 ?????
// {test: /\.(js|jsx)$/, loader: "eslint-loader", exclude: /node_modules/}
// ],
loaders: [
{ test: /\.(js|jsx)$/, exclude: /node_modules/, loader: 'babel-loader',
query: {
presets: ['react', 'es2015'],
//下面是使用 ant-design 的配置文件
plugins: ['react-html-attrs',["import", { "libraryName": "antd" }]]
}},
{ test: /\.less$/, exclude: /node_modules/, loader: 'style!css!postcss!less' },
{ test: /\.css$/, loader: 'style!css!postcss' },
{ test:/\.(png|gif|jpg|jpeg|bmp)$/i, loader:'url-loader?limit=5000&name=img/[name].[ext]' },
{ test:/\.(woff|woff2|svg|ttf|eot)($|\?)/i, loader:'url-loader?limit=5000&name=fonts/[name].[ext]'}
]
},
eslint: {
configFile: '.eslintrc' // Rules for eslint
},
postcss: [
require('autoprefixer') //调用autoprefixer插件,例如 display: flex
],
plugins: [
// html 模板插件
new HtmlWebpackPlugin({
template: __dirname + '/app/index.tmpl.html',
favicon: './ico/favicon.ico'
}),
// 热加载插件
new webpack.HotModuleReplacementPlugin(),
// 打开浏览器
new OpenBrowserPlugin({
url: 'http://localhost:8090/#/login'
}),
// 可在业务 js 代码中使用 __DEV__ 判断是否是dev模式(dev模式下可以提示错误、测试报告等, production模式不提示)
new webpack.DefinePlugin({
__DEV__: JSON.stringify(JSON.parse((process.env.NODE_ENV == 'dev') || 'false'))
}),
// 定义jQuery全局变量
new webpack.ProvidePlugin({
$:"jquery",
jQuery:"jquery",
"window.jQuery":"jquery"
}),
],
devServer: {
proxy: {
// 凡是 `/WHP.HydroPower` 或者 `/WHP.SSO` 开头的 http 请求,都会被代理到 localhost:8080 上
'/WHP.HydroPower': {
target: 'http://localhost:8080',
secure: false
},
'/WHP.SSO': {
target: 'http://localhost:8080',
secure: false
}
},
contentBase: "./public", //本地服务器所加载的页面所在的目录
colors: true, //终端中输出结果为彩色
historyApiFallback: true, //不跳转
inline: true, //实时刷新
hot: true // 使用热加载插件 HotModuleReplacementPlugin
}
}
感谢两位的回答,我检查了一下代码,发现这个插件在运行时会在函数中传入jQuery这个变量,但是奇怪的是jquery并没有在这个插件之前被打包。因此我在插件源码的开头import了jquery,这个报错也就没有了。感谢两位的提供的思路!