Javascript 使用 webpack 加载引导程序时“未定义 jquery”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38825936/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:54:20  来源:igfitidea点击:

'jquery is not defined' when using webpack to load bootstrap

javascriptjquerynode.jstwitter-bootstrapwebpack

提问by Junchao Gu

I am just starting to learn to use Webpack (previously I just use the manual way to include individual scripts separately). And I used bootstrap-loaderfor loading bootstrap. Here is my webpack.config.js

我刚刚开始学习使用 Webpack(以前我只是使用手动方式单独包含单个脚本)。我用于bootstrap-loader加载引导程序。这是我的 webpack.config.js

var path = require("path")
var webpack = require('webpack')
var BundleTracker = require('webpack-bundle-tracker')

module.exports = {
    context: __dirname,

    entry: './assets/js/index', // entry point of our app. assets/js/index.js should require other js modules and dependencies it needs

    output: {
        path: path.resolve('./assets/bundles/'),
        filename: "[name]-[hash].js",
    },

    plugins: [
        new BundleTracker({filename: './webpack-stats.json'})
    ],

    module: {
        loaders: [
            { test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel-loader'}, // to transform JSX into JS
            { test: /\.css$/, loader: 'style-loader!css-loader'}, // to transform css
            // images
            { test: /\.png$/, loader: 'url-loader?limit=100000'},
            { test: /\.jpg$/, loader: 'file-loader'},
            // bootstrap image files
            { test: /\.(woff|woff2)(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=application/font-woff'},
            { test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=application/octet-stream'},
            { test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: 'file'},
            { test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=image/svg+xml'}
        ],
    },

    resolve: {
        modulesDirectories: ['node_modules', 'bower_components'],
        extensions: ['', '.js', '.jsx'],
        jquery: './vendor/jquery/jquery.js',
    },
}

And here is my entry.js

这是我的 entry.js

global.jQuery = global.$ = require('jquery');
require('bootstrap-loader');

This seems to work. However, I used this before and it did not work:

这似乎有效。但是,我之前使用过它,但它不起作用:

window.jQuery = window.$ = require('jquery');

I found the line above suggested by so many people. But I just simply get errors when load the page. Just some examples: some SO question, webpack issue, another SO question.

我发现上面有很多人建议的行。但我只是在加载页面时出现错误。只是一些例子:some SO questionwebpack issueanother SO question

Later I found this question, and this question. So the page actually works with bootstrap js functionality working as well.

后来我发现了这个问题,还有这个问题。因此,该页面实际上也可以与 bootstrap js 功能一起工作。

I will add my package.json as well in case it is relevant:

如果相关,我也会添加我的 package.json :

{
  "author": "franklingu",
  "dependencies": {
    "babel": "^6.5.2",
    "babel-core": "^6.13.2",
    "babel-loader": "^6.2.4",
    "bootstrap-loader": "^1.2.0-beta.1",
    "bootstrap-sass": "^3.3.7",
    "extract-text-webpack-plugin": "^1.0.1",
    "jquery": "^3.1.0",
    "node-sass": "^3.8.0",
    "resolve-url-loader": "^1.6.0",
    "sass-loader": "^4.0.0",
    "webpack": "^1.13.1",
    "webpack-bundle-tracker": "0.0.93"
  },
  "devDependencies": {
    "babel-core": "^6.13.2",
    "babel-loader": "^6.2.4",
    "css-loader": "^0.23.1",
    "file-loader": "^0.9.0",
    "node-sass": "^3.8.0",
    "resolve-url-loader": "^1.6.0",
    "sass-loader": "^4.0.0",
    "style-loader": "^0.13.1",
    "url-loader": "^0.5.7",
    "webpack": "^1.13.1"
  }
}

I am new to webpack but I am not new to JS. I am wondering why window.$is not working.

我是 webpack 的新手,但我对 JS 并不陌生。我想知道为什么window.$不工作。

And I wonder, for webpack, why some people suggested this in plugins:

我想知道,对于 webpack,为什么有些人在插件中建议这样做:

        new webpack.ProvidePlugin({
            'window.jQuery': 'jquery',
            'window.$': 'jquery',
        })

Some people are suggesting this (did not work for me either):

有些人建议这样做(也不适合我):

 resolve: {
    alias: {
        jquery: "jquery/src/jquery"
    }
}

I played with node for a while back then and I remembered that node makes use of request js for loading(I am not very clear about differences between common vs require vs amd though). But why some people mention common js?

那时我玩了 node 一段时间,我记得 node 使用 request js 进行加载(尽管我不太清楚 common 与 require 与 amd 之间的区别)。但是为什么有人提到普通的js呢?

I was developing backend for some time and just started frontend--so many questions are popping up. It would just enough if you provide me with some link to some guide to read which can clear my doubts/build my basic understanding of these.

我开发后端有一段时间了,刚刚开始前端 - 突然出现了很多问题。如果你给我提供一些阅读指南的链接就足够了,这可以消除我的疑虑/建立我对这些的基本理解。

回答by Jorawar Singh

Add this as plugin

将此添加为插件

  new webpack.ProvidePlugin({
   $: "jquery",
   jQuery: "jquery"
  })

and you should be able to have jquery in your whole project.

并且您应该能够在整个项目中使用 jquery。

If issue persists after adding the plugin, try restarting your nodejsserver. Remember to install jqueryusing npm install --save jquery.

如果添加插件后问题仍然存在,请尝试重新启动nodejs服务器。记得安装jquery使用npm install --save jquery.

回答by Niels Steenbeek

Plugin is not needed. Just use following as entry:

不需要插件。只需使用以下作为条目:

entry: [
    'jquery', //will load jquery from node_modules
    './assets/js/index',
]

Then in ES6+ file use:

然后在 ES6+ 文件中使用:

import $ from "jquery";

回答by CodeHacker

I know this is a bit old, but I managed to do it like that :

我知道这有点旧,但我设法这样做:

global.jQuery = require('jquery'); require('bootstrap');

global.jQuery = require('jquery'); 要求('引导');

回答by thargenediad

I want to share my findings for any future developer who might have the same use-case I do.

我想与未来可能拥有与我相同用例的任何开发人员分享我的发现。

I had the requirement to only create a vendor bundle and not an app bundle for an AngularJS(1.7.2) app, using Webpack 4(4.16.4). I think because I was only creating a vendor bundle, none of the other solutions worked. Only expose-loaderworked for me, like so:

我需要使用Webpack 4(4.16.4)仅创建供应商包,而不是为AngularJS(1.7.2) 应用程序创建应用程序包。我认为因为我只是创建了一个供应商捆绑包,其他解决方案都不起作用。只对我有用,就像这样:expose-loader

    // webpack.config.js
    module: {
        rules: [
            {
                test: require.resolve('jquery'),
                use: [{
                        loader: 'expose-loader',
                        options: 'jQuery'
                    },
                    {
                        loader: 'expose-loader',
                        options: '$'
                    }
                ]
            }
        ]
    }

For more information: https://github.com/webpack-contrib/expose-loader

更多信息:https: //github.com/webpack-contrib/expose-loader