Embedding a transpiled .js file in HTML using ExpressJS as a static resource

ExpressJS setup to serve transpiled TypeScript files is giving me trouble. Whenever I try to access /components/foo.js, I keep getting a 404 error.

/* /dist/server.js: */
var express = require('express');
var app = express();
var path = require('path');

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

app.use('/components', express.static(path.join(__dirname, '/dist/components')));

var options = {
    root: __dirname + '/dist/components/',
};

app.get('/', function(req: any, res: any) {
    res.sendFile('/index.html', options);
});

app.listen(8090);
<!-- /public/index.html -->
<html>
    <head>
        <title>demo</title> 
        <script src="/components/foo.js" type="module"></script>
    </head>   
    <body>
        <h1>hello</h1>
    </body>
</html>  

Need help with optimizing folder structure and setting up the server.ts file to successfully include transpiled .js files in my index.html file.

Question: How can I properly configure my folder structure and server.ts to include certain transpiled .js files in my index.html?

P.S.: Came across this SO question, tried their method but failed. Need clarity on what they're doing differently.

Answer №1

What is the best approach to organize the directory structure and server.ts for including specific transpiled .js files in my index.html?

To achieve this, I recommend serving the folder containing the transpiled code as a static directory, ideally using a virtual path.

You can easily serve the components folder assuming it includes safely transpiled codes meant for public access.

app.use('/static', express.static(__dirname + '/components')); // Both server.js and components are located in the same folder

// Afterwards, in your html you can reference the scripts with an absolute path
<script src="/static/foo.js" type="module"></script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering an issue when attempting to establish a connection to Redis using a cache manager within a Nest

Incorporating the NestJS framework into my project and utilizing Cash Manager to connect with Redis cache. Successfully connected with Redis, however encountering an error when attempting to use methods like set/get which shows 'set is not a function& ...

Setting headers in Node using express-http-proxy before proxying data is an effective way to customize

When attempting to proxy to a specific address, I need to set the header of the proxy beforehand. It's like an interceptor for me. Currently, I am using the express-http-library and express with Node.JS. However, my code so far doesn't seem to be ...

Retrieving the body of a response in NodeJS Express after making a POST request

I'm facing a challenge with NodeJS and Express that appears to be as simple as "Hello World," but it has been confusing me all day. Here is my NodeJS POST code: app.post('/evaluateScore', (req, res) => { output = calculators .evalu ...

There are no matching overloads in React for this call

Below is an error message in the code. It seems to be related to the usage of <IHistorical[]> in useQuery, but unfortunately, I haven't found a solution for it yet. Overload 1 of 2, '(props: Props | Readonly<Props>): ReactApexChart& ...

TypeScript in Angular causing lodash tree shaking failure

I am currently working on a large project that involves TypeScript. Various attempts have been made to optimize the use of lodash in my project. Before making any conclusions, I believe it is important to review the outcomes of my efforts. The command I ...

When you make a POST request to an express API, the properties are not clearly defined

Just getting into Vue.JS and experimenting with creating a basic MEVN to-do list app for practice. I keep encountering an issue when trying to send a POST request to my express server, receiving the error message: TypeError: Cannot read properties of unde ...

Error: XYZ has already been declared in a higher scope in Typescript setInterval

I've come across an interesting issue where I'm creating a handler function and trying to set the current ref to the state's value plus 1: const useTimer = () => { const [seconds, setSeconds] = useState(0); const counterRef = useRef(n ...

Vue is encountering difficulties resolving the index.vue file located in the parent directory

Having trouble importing a component from the path folder, I keep encountering an error message stating "Cannot find module './components/layout/Navbar'. Vetur(2307)". This is how I am attempting to import the component: import Navbar from "./c ...

Apologies, but there was an error attempting to differentiate 'nombreyo'. Please note that only arrays and iterables are permitted for this action

Encountering an error while attempting to display a class in the HTML. <li> <ul> <li *ngFor="let refac of refactormodel" > -- word_to_rename: {{refac.word_to_rename}} -- renowned_word: {{refac.renowned_word}} ...

Working with MongoDB in Express using Mongoose

I am currently working with express js and mongoose, storing data in a collection named 'users'. I'm curious about how to change the name of the collection. Below is the snippet of my code: app.post('/signup', (req, res, next) =&g ...

How Angular can fetch data from a JSON file stored in an S3

I am attempting to retrieve data from a JSON file stored in an S3 bucket with public access. My goal is to parse this data and display it in an HTML table. http.get<Post>('https://jsonfile/file.json').subscribe (res => { cons ...

Vue + TypeScript prop type issue: "'Foo' is intended as a type, but is being treated as a value in this context."

As a newcomer to TypeScript and the Vue Composition API, I encountered an error that left me puzzled: I have a component that requires an api variable as a prop, which should be of type AxiosInstance: export default defineComponent({ props: { api: A ...

Converting Jade to HTML in Simple Steps

I have been utilizing the express skelton framework to build an application. Since I am not familiar with jade language, I decided to convert these files to html. However, my current issue is that there are 2 lines in the app.js file that I need to modify. ...

Send the user to an Angular route once they have successfully authenticated with Google

I'm facing an issue with redirecting users to an Angular route. Here's the scenario: When I'm on the login page and click on Google login, I get redirected to Google for authentication. After successfully logging in, I want to be redirecte ...

Utilizing TypeScript to define the parameter of a method within a generic interface by extracting a value from the generic type

In search of defining a versatile interface that can manage any Data type, I came up with an idea. This interface includes a dataKey property which simply holds a value of keyof Data. Additionally, it features a handler function where the parameter type sh ...

Exploring the concept of union return types in TypeScript

Hello, I am facing an issue while trying to incorporate TypeScript in a way that may not be its intended use. I have created a custom hook called useGet in React which can return one of the following types: type Response<T> = [T, false, false] | [nul ...

Disregarding TypeScript import errors within a monorepo ecosystem

In my Turborepo monorepo, I have a Next.js app package that imports various components from a shared package. This shared package is not compiled; it simply contains components imported directly by apps in the monorepo. The issue arises with the shared co ...

Accessing a value within a JSON body response can be done by utilizing the Request module to send GET requests to an external API

Recently, I started working on a project using Express and Node.js to build a simple API that fetches data from an external source. When I run the code provided below and input my /api/posts/tech endpoint into Insomnia, I get back a response containing a J ...

I am experiencing an issue with the PUT method on my API as it is not correctly setting the req.body data

Below is the code snippet for implementing the PUT method: [/api/[id].ts] case "PUT": try { const user = await UserModel.findOneAndUpdate( { _id: id, }, { $set: req.body, ...

What is the best way to retrieve all the keys from an array?

I am looking to retrieve the address, latitude, and longitude data dynamically: let Orders= [{ pedido: this.listAddress[0].address, lat: this.listAddress[0].lat, lng: this.listAddress[0].lng }] The above code only fetches the first item from the lis ...