繁体   English   中英

如何使用webpack在nodejs应用程序中包含jquery?

[英]How to include jquery in nodejs app using webpack?

这是我的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来启动我的节点应用程序时,它需要jquery并引发以下错误。

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

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

jQuery位于全局上下文中(窗口)

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

ProviderPlugin

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

使用nodejs时,您可以创建Web应用程序的服务器端,而jquery是一个JS库,该库允许您操作网页客户端的DOM,因此jquery必须在HTML页面上使用。 相反,必须在服务器端创建一个简单的http服务器,该服务器将正确的html页面发送到客户端。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM