我正在将现有的webapp从requirejs移动到webpack。
我对导入/填充jQuery的方式有疑问。
在我的捆绑js中,我在bootstrap javascript中收到$ is not a function
错误。
当我在捆绑脚本中console.log($)
时,它会显示一个空对象:object {}
我假设这是因为没有任何东西从jQuery导出,因为它传统上将$设置为窗口对象并完成。
一些研究指出我使用webpack插件(请参阅下面的webpack.config.js),但这似乎并不能解决问题。
我的设置有什么问题吗?
由于
我的webpack.config.js:
var path = require('path');
var webpack = require('webpack');
module.exports = {
//devtool: 'source-map',
entry: ['./mobile.js'],
resolve: {
root: "./js/",
alias: {
jquery: 'libs/jquery-1.9.1',
underscore: "libs/lodash-1.0.1",
//backbone: 'libs/backbone-1.0.0',
backbone: 'libs/backbone-0.9.10',
bootstrap: "libs/bootstrap-2.3.1",
......
}
},
resolveLoader: {
root: path.join(__dirname, 'node_modules')
},
output: {
path: './',
filename: 'bundle.js'
},
plugins: [
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
"window.jQuery": "jquery"
})
],
module : {
loaders: [
{ test: /\.html$/, loader: "text" },
{ test: /\.json$/, loader: "json" }
]
}
}
违规的编译捆绑代码:
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(__webpack_provided_window_dot_jQuery) {/* ===================================================
* bootstrap-transition.js v2.3.1
* http://twitter.github.com/bootstrap/javascript.html#transitions
* ===================================================
* Copyright 2012 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ========================================================== */
!function ($) {
console.log($); //THIS GIVES THE EMPTY OBJECT {}
"use strict"; // jshint ;_;
/* CSS TRANSITION SUPPORT (http://www.modernizr.com/)
* ======================================================= */
$(function () { //$ IS NOT A FUNCTION OCCURS HERE
$.support.transition = (function () {
.........
.........
答案 0 :(得分:2)
您还可以尝试exports-loader
:
npm install --save-dev exports-loader
并配置:
{
include: require.resolve('libs/jquery-1.9.1'),
loader: 'exports-loader?window.jQuery'
}
或问题可能在于ProviderPlugin
没有读取jquery
别名,请尝试:
new webpack.ProvidePlugin({
$: "libs/jquery-1.9.1",
jQuery: "libs/jquery-1.9.1",
"window.jQuery": "libs/jquery-1.9.1"
})