jquery - 如何使用 webpack 在 Node.js 应用程序中包含 jquery?

标签 jquery node.js webpack webpack-2

这是我的 webpack.config.js

var webpack = require("webpack");

module.exports = {
    entry: './app.js',
    output: {
        filename: './bundle.js'
    },
    module: {
        loaders: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                loader: 'babel-loader',
                query: {
                    presets: ['es2015']
                }
            }
        ],
    },
    plugins: [
        new webpack.ProvidePlugin({
            $: "jquery",
            jQuery: "jquery"
        })
    ]
};

这是我的 app.js

var $ = require('jquery');
global.jQuery = $;
global.$ = $;
require('jquery');
console.log('Hello from Webpack');
$('#serviceContainer').hide();

因此,当我运行 Node app.js 来启动我的 Node 应用程序时,它需要 jquery 并且抛出以下错误。

 throw new Error( "jQuery requires a window with a document" );

所以我需要知道如何使用webpack在nodejs中包含jquery。如果有人知道请帮忙。提前致谢!!

最佳答案

jQuery 处于全局上下文(窗口)

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

提供者插件

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

关于jquery - 如何使用 webpack 在 Node.js 应用程序中包含 jquery?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46420280/

相关文章:

javascript - 不能扩展一个类,额外的方法未定义

npm - 字段 'browser' 不包含有效的别名配置

javascript - bx-slider 左右滑动手势支持

javascript - Jquery动画三个按钮来进行开关

javascript - Heroku 返回 400 错误请求响应 (Socket.IO Node.js)

node.js - 使用 superagent 通过管道传输可读流

javascript - WebPack配置-正确的代码是什么,它是什么意思

javascript - 如何在ajax请求中生成动态数据对象

javascript - 警报后焦点集中在输入字段上

node.js - ** (CaseClauseError) 没有匹配 : :eacces - Building release with MIX_ENV=prod 的 case 子句