Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
776 views
in Technique[技术] by (71.8m points)

javascript - How can I bundle Express Js (NodeJs) and Pug engine using Webpack?

Introduction: I have used ExpressJs framework with node as server and pug as a template engine. I want to bundle .js , .pug & .css.

I'm aware of webpack (module bundler) configuration for static files (CSR-client side rendering) . For CSR appoach we will follow the steps below.

  1. Bundle all files using webpack
  2. Host html & bundle.js(created by webpack earlier) using server (iis / npm serve or of any other choice).

So, I tried the same with ExpressJs which is(SSR-server side rendering), webpack bundled all files (excluding NodeModules) including index.js which contains server(nodeJs).

  • Is it the right ? If so how to serve the files using the bundled host inside index.js?
  • If that is totally a wrong then, can you please suggest some good practice?

Folder Structure

index.js

var express = require('express');
var cookieParser = require('cookie-parser');//cookie Parser
var bodyParser = require('body-parser');//JSON data

//Inbuild Functions
const userManagementRoutes = require('./src/routes/userManagementRoutes');
const app = express();

//view Engine
app.set('view engine', 'pug');
app.set('views', './src/views/userManagement');

//for cookie parser
app.use(cookieParser());

// for parsing application/xwww-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true })); 

//Static File Server
app.use('/Malips', express.static('public'));

//Routes
app.use('/', userManagementRoutes)

//server
app.listen(3000);

src outesUserManagementRoutes.js

const express = require('express');
const loginController = require('../controllers/userManagement/loginController');

const router = express.Router();

router.get('/', function(req, res){
    res.render('app.pug');
});

router.get('/Login', function(req, res){
    res.render('login.pug');
});

router.post('/Login', function(req, res){
    const { userName, password } = req.body;
    if(loginController(userName, password)){
        res.render('home.pug',{userName : userName});
    }
    else{
        res.render('login.pug',{errorMessage : 'Invalid Credentials'});
    }
});

module.exports  = router;

srccontrolleruserManagementLoginController

module.exports = function LoginController(userName, password)
{
    if(userName == '[email protected]' && password == 'admin')
        return true;

    else
        return false;    
}

srcviewsuserManagementLogin.pug

extends _layout.pug
block content
    div 
    form(action="/Login", method="post")
        label UserName
        br 
        input(type='email', name = 'userName' required autofocus)
        br
        label Password
        br
        input(type='text' name = 'password' required autofocus)
        br
        input(type="submit")
        h3 #{errorMessage}

package.json

  "scripts": {
    "start": "nodemon index.js",
    "test": "echo "Error: no test specified" && exit 1"
  },

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I found one way where the template engine(.pug) remains the same and only the Javascript will bundles.

.babelrc

{
    "plugins": ["@babel/plugin-proposal-class-properties", "@babel/plugin-transform-runtime"],
    "presets": ["@babel/preset-env"]
}

webpack.config.js

const path = require('path');
const nodeExternals = require('webpack-node-externals');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlWebpackPugPlugin = require('html-webpack-pug-plugin');

module.exports = {
    mode: 'development',
    entry: './index.js',
    output: {
        path: path.resolve(__dirname, './dist'),
        filename: 'app-bundle.js'
    },


target: 'node', 
externals: [nodeExternals()],

module: {
    rules:[
        {
            test: '/.(js|jsx)$/',
            exclude: /node_modules/,
            use: 'babel-loader'
        },
        {
            test: '/.pug$/',
            use: 'pug-loader'
        },
        {
            test: '/.css$/',
            use: ['styles-loader', 'css-loader']
        }
    ]
},

plugins: [
    
    new HtmlWebpackPlugin({
        template: 'src/views/_layout.pug',
        filename: '_layout.pug'
    }),
    new HtmlWebpackPlugin({
        template: 'src/views/app.pug',
        filename: 'app.pug'
    }),
    new HtmlWebpackPlugin({
        template: 'src/views/home.pug',
        filename: 'home.pug'
    }),
    new HtmlWebpackPlugin({
        template: 'src/views/login.pug',
        filename: 'login.pug'
    }),

    new HtmlWebpackPugPlugin()
]


}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...