Proper way of compiling TypeScript repo for import in another TypeScript repo?

I have struggled with this for some time. I have this now in lib-a:

{
  "compilerOptions": {
    "module": "CommonJS",
    "target": "ES5",
    "lib": ["es2020"],
    "outDir": "host",
    "rootDir": ".",
    "sourceMap": true,
    "moduleResolution": "node",
    "allowSyntheticDefaultImports": true,
    "strictNullChecks": true,
    "strict": true,
    "esModuleInterop": true,
    "noUncheckedIndexedAccess": true,
    "baseUrl": ".",
    "noErrorTruncation": true,
    "types": ["node"],
    "typeRoots": ["node_modules/@types"],
    "noImplicitAny": true,
    "declaration": true
  },
  "include": ["*.ts", "**/*.ts", "*.d.ts"],
  "exclude": ["node_modules", "host"]
}

I have this in lib-b, which does import thedefault from 'lib-a':

{
  "compilerOptions": {
    "module": "CommonJS",
    "target": "ES5",
    "lib": ["es2020", "dom"],
    "outDir": "host",
    "rootDir": ".",
    "sourceMap": true,
    "moduleResolution": "node",
    "strictNullChecks": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "esModuleInterop": true,
    "noUncheckedIndexedAccess": true,
    "baseUrl": ".",
    "allowJs": true,
    "noErrorTruncation": true,
    "types": ["node"],
    "typeRoots": ["node_modules/@types"],
    "noImplicitAny": false,
    "paths": {
      "~/*": ["./*"],
      "~": ["./index.ts"]
    }
  },
  "include": ["*.ts", "**/*.ts", "*.d.ts"],
  "exclude": ["node_modules", "./host/**/*"]
}

I am seeing this in lib-b on thedefault:

console.log(thedefault)
// { default: [Function: myDefaultFunction] }

Here is what I would like:

  1. Compile the .js, .d.ts, and .js.map output for each .ts file in each project, so it works on ES5 systems (you can just load the file and it works, don’t get errors like import is not a function or whatever, because the import statements were left in the build/*.js files).
  2. The output *.js files don’t have import, export, etc., they are compiled down to systems that don’t include ES6 features.
  3. Don’t want to use the type: 'module' option in package.json, or to specify .mjs files. I want to have plain .ts files and do it without that type option.
  4. I would like to use all ESNext features in my TS code.

How do I do this?

I have tried:

{
  "compilerOptions": {
    "module": "ESNext",
    "target": "ES5",
    "lib": ["es2020", "dom"],
    "outDir": "host",
    "rootDir": ".",
    "sourceMap": true,
    "moduleResolution": "node",
    "strictNullChecks": true,
    "strict": true,
    "esModuleInterop": true,
    "noUncheckedIndexedAccess": true,
    "baseUrl": ".",
    "allowJs": true,
    "noErrorTruncation": true,
    "types": ["node"],
    "typeRoots": ["node_modules/@types"],
    "noImplicitAny": false,
    "paths": {
      "~/*": ["./*"],
      "~": ["./index.ts"]
    }
  },
  "include": ["*.ts", "**/*.ts", "*.d.ts"],
  "exclude": ["node_modules", "./host/**/*"]
}

That is:

    "module": "ESNext",
    "target": "ES5",

That would make sense to me, but anything other than module: CommonJS results in including the import and export ES6 features in the build files.

Do I need webpack for this or something?

It should be straightforward, some combination of TypeScript config options, but I can’t figure it out.

If I do do:

    "module": "ESNext",
    "target": "ES5",

Then it works at least in node:

console.log(thedefault)
// [Function: myDefaultFunction]

But, then I need webpack to get it to work in the browser. And in Next.js I need to add this to the webpack build via the transpilePackages option, which is annoying. Any way to avoid that and I can just import my compiled module anywhere and it “just works”?

Finding the future position of a non-linear moving object

I am trying to predict where a ship will be in within a given amount of seconds, and I thought that I had accomplished this until the turning velocity reaches a high number and turns into a seemingly 3d spiral projected into 2d space, which is what I don’t understand.

I’ve recreated the code with a set of data rendered on a html canvas to demonstrate this (see below)

What am I doing wrong to cause this spiral effect? It looks like it is making a circle, but on the wrong axis.

https://jsfiddle.net/a5d92s1w/7/

const canvas = document.createElement("canvas");
document.body.appendChild(canvas);
const ctx = canvas.getContext("2d");

// Get a ship's future position in a specified amount of time based on its current velocities
const projectedPosition = (ship, dlta) => {
    const pos = {...ship.position};
    
    // Step through seconds in time and adjust position and angle from each step
    for (let i=0; i < dlta; i++) {
        // Cache current position of ship in time
        const [cx, cy] = [pos.x, pos.y];

        // Add linear velocity to position
        pos.x += ((ship.linearVelocity.x) / 100); 
        pos.y += ((ship.linearVelocity.y) / 100);
        
        // Rotate future direction around current
        const r = (ship.heading + ship.angularVelocity.z * i) * -Math.PI / 180;
        const [cos, sin] = [Math.cos(r), Math.sin(r)];
        pos.x = cx + (cos * (pos.x - cx)) + (sin * (pos.y - cy));
        pos.y = cy + (cos * (pos.y - cy)) - (sin * (pos.x - cx));
    }

    return pos;
}

const draw = () => {
    canvas.width = 1000;
    canvas.height = 1000;

    const ship = {
        position: {x: 500, y: 100}, // Centre on canvas
        angularVelocity: {z: -8.4}, // The velocity that the ship is turning, in Degrees per second
        heading: 35, // The currently angle the ship is facing, in Degrees
        linearVelocity: {x: 4  * 100, y: -6  * 100} // Metres per second, * 100 for canvas purposes
    };
            
    // Draw Red dot for current ship position
    ctx.fillStyle = "red";
    ctx.arc(ship.position.x, ship.position.y, 8, 0, 2 * Math.PI);
    ctx.fill();
            
    // Draw future positions based on ships velocities
    ctx.fillStyle = "green";
    for (let i=1; i < 50; i++) {
        const dlta = i * 4; // Every iteration of loops is 4 seconds
        const proj_position = projectedPosition(ship, dlta); 
        
        ctx.beginPath()
        ctx.arc(proj_position.x, proj_position.y, 8, 0, 2 * Math.PI);
        ctx.fill();
    }
};

draw();

How to show an external div when on hover using Javascript

Is there any way that I can show a external div on hover of a button using pure Javascript.
In my application, there are many icons and I wanted to show a tooltip on hover that should be a external div with some text.

<div class="icons">
      <div class="icon-wrapper" data-label="Delete">Icon Image</div>
      <div class="icon-wrapper" data-label="User">Icon Image</div>
      <div class="icon-wrapper" data-label="Edit">Icon Image</div>
      <div class="icon-wrapper" data-label="Checkbox">Icon Image</div>
      <div class="icon-wrapper" data-label="Settings">Icon Image</div>
    </div>
<div class="tooltip">
      This external div should appened to each "icon-wrapper" div extrally on hover. This div should not be there by deault in the html body.
    </div>

Thanks in advance

I found many example on jQuery but I need it in pure Javascript.

This seems like simular but it’s not working in my use case and its based on ID. It should be based on class and not id in my case.

How do I display the result of Google’s computeRoute API?

I am using the computeRoute post method provided by Google’s Routes API. The method returns a JSON file with the following data :

{
    "routes": [
        {
            "distanceMeters": 99537,
            "duration": "6977s",
            "polyline": {
                "encodedPolyline": "y`hbEqr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CiEiEaDqCwB_BkEyDuEsDkCeCoBuB}A_CqEaHmAkBwCqD}BiC_EiEm@m@y@mAa@y@_DmFuDyFOg@k@sC}@yDiAoGQw@c@mAwDeGcA}Ae@i@QIg@KaAIq@Km@WeBcCmAwAw@cAk@kAGa@Gq@@[B]b@oBt@cEcAuDc@wAmLsc@s@{BqJmWqIoVsIaVcFyNgWws@_DgIg@gBMeAAq@Jo@La@dBaBvG{F|GcGVGZId@?\FXPX\Nb@Dr@Gd@Q`@[\[N]Bk@@o_@sKuA]qEs@kIqBskAu\eHsBcBa@kAUcL}Aui@kGuBc@aBg@_Bo@qXyMkHgDuEeBc[aKsCcAkBw@eG_DaYuOy\qRoBuA_RqNwAcA{BiBmDmCkIgGmPaMkAaAyAyAI_@A_@HYxDiIPAPYQXQ@MX"
            }
        }
    ]
}

The “encodedPolyline” object can be decoded and displayed on a map using Google’s interactive polyline decoder utility.
I want to display this polyline that shows up when using the decoder utility on my map which is in a vue js project.
How would I go about displaying, or decoding the polyline on my map?
I looked around, and I didn’t find an API for the decode utility.
Here is my current vuejs component, just in case:

<template>
  <div>
    <GMapMap
      :center="center"
      :zoom="13"
      map-type-id="terrain"
      style="width: 100%; height: 100%; position: absolute"
      
    >
    </GMapMap>
  </div>
</template>
  
  <script>
export default {
  data() {
    return {
      center: { lat: 31.950695, lng: 35.923022 },
    }
  }
}
</script>

I looked up solutions, and I asked GPT, and checked youtube. I did not have any success finding what I was searching for, and it is not a foreign concept so I just figured I did not know what I was looking for, so I would ask about it on stack overflow so actual people read it and understood what I was looking for. I also tried some Discord communities but I didnt get any responses there.

TL;DR: I want to display a polyline that has many many points on a map. I have an encoded polyline and there is a tool by Google that decodes it, but I don’t know how to use the tool in my project.

console.log is not working in react function component

The console.log in the handleSubmit function not running:

const MyForm = () => {
  // Use useState for each input field
  const [webpageLink, setwebpageLink] = React.useState('');
  const [timeInterval, settimeInterval] = React.useState('');
  const [email, setEmail] = React.useState('');

  // Event handler for the first input field
  const handleInputChange1 = (event) => {
    setwebpageLink(event.target.value);
  };

  // Event handler for the second input field
  const handleInputChange2 = (event) => {
    settimeInterval(event.target.value);
  };

  const handleInputChange3 = (event) => {
    setEmail(event.target.value);
  };

  // Submit handler
  const handleSubmit = () => {
    // Send data to Flask backend
    fetch('http://127.0.0.1:5000/data', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ link: webpageLink, time: timeInterval, clientEmail : email }),
    })
      .then(response => resnponse.JSON())
      .then(result => {
        console.log(result);
        // Handle the response from the Flask backend
      })
      .catch(error => {
        console.error('Error:', error);
      });
  };
  return (
    <>
      <form onSubmit={handleSubmit}>
         <label for ="webpageLink"><p class = "heroSubText color">Link to the webpage:</p></label>
          <input type="text" value ={webpageLink} onChange={handleInputChange1} name="webpageLink" id = "webpageLink" size = "50px" maxlength="9999" required/>
          <label for="timeInterval"><p class = "inputText color">Time interval (minutes):</p></label>
          <input type="number" value={timeInterval} onChange={handleInputChange2} id="timeInterval" name="timeInterval" min="10" max = "999999"step="1" placeholder="10-999999" required/>
          <label for ="email"><p class = "inputText color">Email:</p></label>
          <input type = "email" value={email} onChange={handleInputChange3} id="email" name="email" required size = "50px"/><br/>
          <input type = "submit" value = "GO!" class = "button color"/>
      </form>
    </>
  );
};

ReactDOM.render(<MyForm/>, document.querySelector('#form'));

The post request runs successful and successfully return the data. however, the console.log in the part

.then(result => {
        console.log(result);
        // Handle the response from the Flask backend
      })

does not run. The only way I can make soncole.log to run is writing outside of the inner functions and inside MyForm function.

I have tried man way to make that console.log run but could not. Can anyone please help me with this? thank you.

Client-side JS autocomplete not working with VS Code

When I attempt to write plain client-side JS, I do not get any suggestions or autocomplete at all. Even for something as simple as console.log(), the editor does not provide any method suggestions.

However, when I use a JS runtime such as Deno, this is not the case.

Is this normal behavior?

Thanks!

How do I add pagination to this static blog list page on NextJS? (It uses markdown files as blogs)

I am using nextjs to build a static blog generated from markdown files. I have a function getPostMetadata that gets the data from my “test” folder which holds my markdown files. How do I dynamically add pagination to this blog list? It pulls metadata from markdown files. I tried using this tutorial but I couldn’t make it work for my metadata.

My getPostMetadata component looks like this:

import fs from "fs";
import matter from "gray-matter";

export interface PostMetadata {
    slug: string
    data: any
}

const getPostMetadata = ( path: string): PostMetadata[] => {
    const files = fs.readdirSync(path);
    const markdownPosts = files.filter((file) => file.endsWith(".md"));
    const posts = markdownPosts.map((fileName) => {
      const fileContents = fs.readFileSync(`${path}/${fileName}`, "utf8");
      const matterResult = matter(fileContents);
      return {
        slug: fileName.replace(".md", ""),
        data: matterResult.data,
      };
    });
    return posts;
  };  

export default getPostMetadata

My list of blog pages is in this structure: blog/page.tsx and the component looks like this:

import React from "react";
import getPostMetadata from "@/components/ReusableComponents/getPostMetadata";

export const metadata = {
  title: "Restaurant Insights Blog | Altametrics",
  description: "In-depth articles how-to guides, and resources critical to your restaurant's growth and profitability.",
};

export default function Blog( ) {
  const postMetadata = getPostMetadata("test");

  // Sort posts by date_modified in descending order
  const sortedPosts = postMetadata
  .sort((a: any, b: any) => {
    const dateA = new Date(b.data.date_published) as any;
    const dateB = new Date(a.data.date_published) as any;
    return dateA - dateB;
  });

  // Extract the first post
  const mainPost = sortedPosts[0]

  // Extract the next four posts starting from the second post
  const sidePosts = sortedPosts.slice(1, 4)
  const bottomPosts = sortedPosts.slice(5, 11)

  return (
    <main>
      <section className="articles-hero">
        <div className="mx-3">
          <div className="row mt-3 align-items-start hero_main">
            {mainPost && (
              <div className="col-12 col-sm-12 col-md-12 col-lg-6 col-xl-6 col-xxl-6">
              <div className="position-relative">
                <a className="position-absolute w-100 h-100" href={mainPost.slug}></a>
                <div className="hero_left">
                  <div className="main-img">
                    <img src={`${process.env.NEXT_PUBLIC_CONTENT_URL}/collections/${mainPost.data.article_body.content.heading.image.i_image}`} />
                  </div>
                  <div className="main-description">
                    <span className="badge text-capitalize border text-secondary">{mainPost.data.category}</span>
                    <h1>{mainPost.data.article_body.content.heading.t_title}</h1>
                    <p>{mainPost.data.article_body.content.heading.t_description}</p>
                  </div>
                </div>
              </div>
            </div>
            )}
          </div>
        </div>
    </section>



      {/* ... rest of my code */}
    </main>
  );
}

hover over div, same image to appear in the background

    body{
    max-height:10vh;
    background-repeat: no-repeat;
    justify-content: center;
    align-items: center;
    background-position: center;
    background-size: cover;
    }
    .back-frem {
    width: 100%;
    height: 30rem;
    border-radius: 23px;
    bottom: 60px;
    display: flex;
    justify-content: space-around;
    align-items: center;
}
.back-frem .back-chang {
    margin: 2px;
    height: 191px;
    background: rgb(17, 14, 14);
    overflow: hidden;
    cursor: pointer;
    border-radius: 23px;

}
   .back-frem .back-chang img{
    width: 100%;
    height: 100%;
    object-fit: cover;
}
   .back-frem .back-chang:hover {
    height: 222px;
    width: 1222px;
}


function background1() {
document.querySelector('body').style.background = "url('images/finn-balor-wwejpg.jpg' 'we are')";

}
function background2() {
document.querySelector(‘body’).style.background = “url(‘images/joe.webp’) center center / cover”;
}
function background3() {
document.querySelector(‘body’).style.background = “url(‘images/notoriousbig-048838bf207c4e96ad98793aa4904a5a.jpg’) center center / cover”;

}
function background4() {
document.querySelector(‘body’).style.background = “url(‘images/finn2.webp’) center center / cover”;

}
function background5() {
document.querySelector(‘body’).style.background = “url(‘images/finn3.jpeg’) center center / cover”;

}

ideally want the image of each. div when hover over, to appear in the background and cover the parent div, ideally with buttons so can link GitHub etc. this example would ideally be showing projects. at the moment when div hovered over it is covering the whole body

A variable doesn’t increment because of a for loop in JavaScript [closed]


function checkAndFill() {
    const input = document.getElementById('wordInput');
    const enteredWord = input.value.trim().toLowerCase();
    let filledCount = 0;

    for (const word of words) {
        if (word.word === enteredWord) {
            fillWord(word);
            filledCount++;
        }
    }

    input.value = '';
    console.log(filledCount);
    if (filledCount === words.length) {
        alert("Congratulations! You have filled all the words.");
        confetti({
            particleCount: 100,
            spread: 70,
            origin: { y: 0.6 }
        });
    }
}

For some unknown to me reason the variable filledCount remains 1 throughout the whole program. It gets called the right number of times but it always stays 1. How can I fix this?

I tried console logging the output but I couldn’t find what was causing the issue.

How dos onkeyup function?

Im am a newbee and I don’t andurstand how does “onkeyup” function. Nothing is printed when I type in the login session with this code.

 <section id="login" class="login">
      <div class="container" >


          <form action="/login" method="post" role="form" class="php-email-form p-3 ">
              <div class="form-group">
                <input type="text" name="login" class="form-control" id="login" placeholder="Login" onkeyup="checkLogin" required >
              </div>
              <div class="form-group">
                <input type="password" class="form-control" name="password" id="password" placeholder="Password" disabled="true" required >
              </div>
            
            
            <div class="text-center" disabled="true"><button type="submit">Submit</button></div>
          </form>

        <!--End Contact Form -->

      </div>
    </section><!-- End Login Section -->
  <script>
    function checkLogin(){
      data = {login:$('#login').val()};
      console.log(data)
    }
  </script>

I tried write in the login form and I thought that the login would be printed.

gulp foreach not iterating over all files

I have a function in my gulpfile as below. However, it doesn’t appear to be iterating over all the files in teh build directory. I currently have login.html and reset.html in the buildDir folder, but it only ever iterates over login.html then exits.

Why won’t it iterate over all the files?

/**
 * Injects the contents of styles/{FILENAME,main}.css, scripts/{FILENAME,main}.js into FILENAME.html
 */
async function injectContents() {
    gulp.src(`${buildDir}/**/*.html`)
        .pipe(foreach((stream, chunk) => {
            console.log(chunk.path)
            gulp.src(chunk.path)
                .pipe(inject(gulp.src([`${buildDir}/styles/main.css`, `${buildDir}/styles/${path.basename(chunk.path, '.html')}.css`]), {
                    starttag: '<!-- inject:css -->',
                    removeTags: true,
                    transform: (filePath, file) => file.contents.toString('utf8')
                }))
                // TODO: Readd `-min`
                .pipe(inject(gulp.src([`${buildDir}/scripts/main.js`, `${buildDir}/scripts/${path.basename(chunk.path, '.html')}.js`]), {
                    starttag: '<!-- inject:js -->',
                    removeTags: true,
                    transform: (filePath, file) => file.contents.toString('utf8')
                }))
                .pipe(htmlmin({ collapseWhitespace: true }))
                .pipe(gulp.dest(distDir))
        }))
}

React Routes work on localhost but gives 404 on the server

I’m using React Routes this is what I wrote which works on LocalHost whether I directly go to localhost:3000 or localhost/home

But on the main server (using netlify to host) and custom domain
When I enter localhost/home, it gives me Error 404

return (
    <div className={App ${isIntroIn ? 'intro-in' : ''} ${isPreOut ? 'pre-out' : ''}}>
      
      {!isIntroIn && <Preload isPreOut={isPreOut} />}
      {isPreOut && <Navigate to="/home" replace />}
      <Routes>
        <Route path="/home" element={<Intro isIntroIn={isIntroIn} isPreOut={isPreOut} />} />
      </Routes>
    </div>
  );

Serve Next.js build from a Node/express server in production

I currently have my Node/Express server hosted on Heroku and it serves my bundled React code from Vite like so (vite build outputs dist folder)

const app = express();

app.use(express.static('dist'));

app.use('*', (req, res, next) =>
  // in deployment we send index.html for all additional paths not defined by our express routes
  // react router pushes different paths to window url
  res.sendFile(path.join(__dirname, 'dist', 'index.html'))
);

The vite build command creates a dist folder with an index.html file at the root, so it makes sense how my SPA is served by express in this case. However, I plan to move my client side code over to Next.js for some of the server side rendering benefits, while still having the bundle served by my express backend. But the Next.js build command generates a .next directory with a much different structure and no index.html at the root. I notice in the server/app folder there is something similar but I am not sure if thats what I am supposed to be serving.. (probably a lot I am not understanding here)

Has anyone done this before – serving a bundled next app from their express server in production – and can point me in the right direction?

Having trouble displaying an image from Google Drive in HTML using JavaScript

I’m struggling to show an image from Google Drive on my HTML page using JavaScript. Following online guides hasn’t quite solved it for me.

HTML (index.html):

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Google Drive Image</title>
</head>
<body>
  <img id="imageElement" alt="A lovely image">
  <script src="script.js"></script>
</body>
</html>

JavaScript (script.js):

const fileId = '1BEW9tkgVKlp_ebUc17LkXDH-mnPc4ome';
const imageElement = document.getElementById('imageElement');

async function fetchGoogleDriveImage(fileId) {
  try {
    const response = await fetch(`https://drive.google.com/uc?id=${fileId}`);
    const url = URL.createObjectURL(await response.blob());
    imageElement.src = url;
  } catch (error) {
    console.error('Error fetching the image:', error);
  }
}

fetchGoogleDriveImage(fileId);

Context:

  • Image in Google Drive is set to “Anyone with the link can view.”
  • Despite that, the image doesn’t load in the browser, and the console shows an error.

Additional HTML (with pure html):

<body>
  <img src="https://drive.google.com/uc?id=1BEW9tkgVKlp_ebUc17LkXDH-mnPc4ome" alt="Your Image Alt Text">
</body>

CodePen Example

Any help is appreciated! Thanks.

How would I get the full response from this Axios request?

I’m trying to get some data from a HTTP request (via Axios), however my issue is that I’m unsure of how I can get the “imageUrl” from it.

axios request

As you can see in the above image, this is the response I get. Below is the code I’m currently using:

function getAvatarURL(userID) {
    axios.get(`https://thumbnails.roblox.com/v1/users/avatar-headshot?userIds=${userID}&size=420x420&format=Png&isCircular=false`)
        .then(r => {
            console.log(r.data)
        })
}

r.data.data returns what is in the image.

When I try and do console.log(r.data.data.imageUrl) is simply returns ‘Undefined’

How would I go about getting the imageUrl from this?