简体   繁体   English

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

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

This is my webpack.config.js 这是我的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"
        })
    ]
};

this is my app.js 这是我的app.js

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

So when i run node app.js to start my node app, it is requiring jquery and it is throwing the below error. 因此,当我运行node app.js来启动我的节点应用程序时,它需要jquery并引发以下错误。

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

So i need to know how to include jquery in nodejs using webpack. 所以我需要知道如何使用webpack将jquery包含在nodejs中。 If anyone knows please help.Thanks in advance!! 如果有人知道,请帮忙。谢谢!!

jQuery to be in the global context (window) jQuery位于全局上下文中(窗口)

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

ProviderPlugin ProviderPlugin

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

With nodejs you can create the server-side of your web application while jquery is a JS library which allows you to manipulate the DOM of a web page client-side so jquery must used on your HTML pages. 使用nodejs时,您可以创建Web应用程序的服务器端,而jquery是一个JS库,该库允许您操作网页客户端的DOM,因此jquery必须在HTML页面上使用。 Server-side, instead, you must create a simple http server that send to the client the correct html page. 相反,必须在服务器端创建一个简单的http服务器,该服务器将正确的html页面发送到客户端。

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

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