简体   繁体   中英

How to include jquery in nodejs app using webpack?

This is my 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

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.

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

So i need to know how to include jquery in nodejs using webpack. If anyone knows please help.Thanks in advance!!

jQuery to be in the global context (window)

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

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. Server-side, instead, you must create a simple http server that send to the client the correct html page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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