pugjs / pug

Pug – robust, elegant, feature rich template engine for Node.js
https://pugjs.org
21.7k stars 1.95k forks source link

Include JS files in a smart way #3441

Closed ComputMagnac closed 4 months ago

ComputMagnac commented 4 months ago

Pug Version: pug@3.0.3 Node Version: bun version 1.1.18

Input Pug

// INDEX.PUG
script(type='text/javascript', src='/files/js/index.js')

doctype html 
html
    include include/header.pug
    body 
        include include/navbar.pug
        h1 Some Content
// NAVBAR.PUG
script(type='text/javascript', src='/files/js/navbar.js')

div(class=navbar)
    h4 element1 
    h4 element2 
    h4 element3

Expected HTML

<!DOCTYPE html >
<html>
    <head>
         /* CONTENT */
    </head>
    <body>
        <div>
            <h4>element1 </h4>
            <h4>element2 </h4>
            <h4>element3</h4>
        </div>
        <h1>Some Content</h1>
         <script type="text/javascript" src="/files/js/navbar.js"></script>
         <script type="text/javascript" src="/files/js/index.js"></script>
    </body>
</html>

Actual HTML

<script type="text/javascript" src="/files/js/index.js"></script>
<!DOCTYPE html >
<html>
    <head>/* CONTENT */</head>
    <body>
        <script type="text/javascript" src="/files/js/navbar.js"></script>
        <div>
            <h4>element1 </h4>
            <h4>element2 </h4>
            <h4>element3</h4>
        </div>
        <h1>Some Content</h1>
    </body>
</html>

Additional Comments

i would argue it make sense that Pug moves the appropriate scripts tag. I tried to implement a dynamic aproach mixing JS & Pug such as

    addScript(filePath: string)
    {
        console.log("Adding: " + filePath)
        this.scriptRequires.push(filePath);
    }

    getScripts()
    {
        return this.scriptRequires;
    }

And then

// NAVBAR.PUG
- template.addScript("navbar");
div(class=navbar)
    h4 element1 
    h4 element2 
    h4 element3

But it was not working because the execution is done instantly. So if I wanted to implement my scripts in the header, my navbar css would not be implemented so my header would only contain the index Script