簡體   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