Obtain the file path relative to the project directory from a Typescript module that has been compiled to JavaScript

My directory structure is as follows:

- project
|- build
|- src
 |- index.ts
 |- file.txt

The typescript code is compiled to the build directory and executed from there. I am seeking a dependable method to access file.txt from the compiled module without having to adjust for the build output location.

One possible solution could be assuming that the file can be found at ../src/file.txt relative to the index.js in the build directory. However, if the build output changes, this assumption would need to be updated accordingly.

Is there a way to set the root directory as an environment variable before compiling the typescript?

Answer №1

For those utilizing webpack, consider adding a resolve option as outlined in the documentation here: https://webpack.js.org/configuration/resolve/

Here's an example:

const path = require('path');

module.exports = {
  //...
  resolve: {
    alias: {
      Utilities: path.resolve(__dirname, 'src/utilities/'),
      Templates: path.resolve(__dirname, 'src/templates/'),
    },
  },
};

If you are using vscode, you can also utilize jsconfig.json and configure compilerOptions as described in the documentation: https://code.visualstudio.com/docs/languages/jsconfig

Here's a sample configuration:

{
  ...
  "compilerOptions": {
    "target": "es2015",
    "module": "esnext",
    "baseUrl": ".",
    "paths": {
      "@assets/*": ["src/assets/*"],
      "@background/*": ["src/background/*"],
      "@frontend/*": ["src/frontend/*"],
      "@mixins/*": ["src/frontend/mixins/*"]
    }
  }
}

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

Concealing the submit button until a file has been selected

How can I make the submit button invisible until a file is selected? <form action="upload.php" method="POST" enctype="multipart/form-data"> <input type="file" name="imageURL[]" id="imageURL" /> <input type="submit" value="submi ...

How to utilize a parameter value as the name of an array in Jquery

I am encountering an issue with the following lines of code: $(document).ready(function () { getJsonDataToSelect("ajax/json/assi.hotel.json", '#assi_hotel', 'hotelName'); }); function getJsonDataToSelect(url, id, key){ ...

Does TypeGraphQl have the capability to automatically format SQL queries?

I am utilizing TypeORM in conjunction with TypeGraphQL. I am curious about the SQL query result that TypeGraphQL provides. For instance, if I have a User Table with numerous columns and a simple resolver like this: @Resolver() class UserResolver { @Q ...

Effortlessly switch between CSS animation styles while adjusting animation settings

My HTML element with animation is defined as follows: <div id="box"></div> The box starts by moving 200 pixels to the right, taking 4 seconds to complete. .anim { animation-name: anim; animation-duration: 4s; animation-t ...

Avoid re-rendering the page in Nuxt when adjusting dynamic parameters

My page has two dynamic parameters that trigger the fetch method to run again when the URL params are changed. I want to avoid this behavior. Fetch Method: async fetch() { await this.getFlightResult(); } Get Result Method: async getResult() { th ...

What could be causing the double invocation of render() in ReactNative?

I'm currently working on an app with a single screen displaying a map centered on the user's current coordinates. In my code below, I've set the latitude and longitude to null in the state of the App component. Using the componentDidMount() ...

The jQuery animation concludes before its anticipated completion

I'm currently facing a small issue with a jQuery animation. The HTML code I have is as follows: <div id="menu"> <a id="menu-about" href="/">About...</a><br /> <a id="menu-ask" href="/">Ask me a question</a> ...

What is the specific process that Express.js uses to manage errors?

Regarding the trivial matter, it is common knowledge that Express comes with a built-in default error handler that expects four arguments (err, req, res, next) to manage "synchronous exceptions" such as ReferenceError, TypeError, etc: UPDATE: The query at ...

Is there a way to set up IIS to host my NodeJS REST API on a unique URL without having to expose any additional ports?

Recently, my organization provided me with a Windows Server running Windows Server 2019 and IIS. I have successfully configured PHP and MySQL to host my website on this server using IIS. However, I have now developed a new service using Node.js that serve ...

Is there a way to make all cards in material ui the same height?

My challenge lies in rendering cards in a grid list using material-ui. Each card comprises an image file at the top and some content in the rest of the space. However, variations in text content cause differences in card height. Despite several attempts, I ...

Executing concurrent HTTP requests in groups in Node.js via async handling

My code structure is like this: readLine.on('line', function (line) { async.parallel([ function (callback) { // Sending HTTP request #1 with JSON and getting JSON as a result }, function (callback) { // Sending HT ...

I keep encountering an issue with getJson

A snippet of my JavaScript code retrieves a JSON object from a URL. Here is the portion of the code in question: <script> $(document).ready(function(){ $("button").click(function(){ $.getJSON('url_address', {}, function(data) { ...

What is the best way to modify or revise meta fields for individual products in order to retrieve multiple images for each product in Shopify?

What is the process for updating or editing meta fields to display multiple images of each product on Shopify? ...

Issue: Unable to import certain modules when using the Typescript starter in ScreepsTroubleshooting: encountering

Having trouble with modules in the standard typescript starter when transferring to screeps. One issue is with the following code: import * as faker from 'faker'; export function creepNamer() { let randomName = faker.name.findName(); return ...

How do I leverage one of my props in React to iterate through my JSON data?

My goal is to utilize props.type to modify the mapping of the JSON in the H5 section. I attempted to accomplish this similar to how I did with the className, but unfortunately, I haven't been able to find the correct method. import text from "../ ...

You are only able to click the button once per day

I am working on a button that contains numeric values and updates a total number displayed on the page when clicked. I would like this button to only be clickable once per day, so that users cannot click it multiple times within a 24 hour period. Below i ...

Steps for creating a node.js and ejs file to deploy on 000webhost

I have developed a simple todo-app using node.js and ejs templating. My goal is to host it using 000webhost, a free web-hosting service. I successfully hosted a react app for free on this platform by running "npm run build", which converted the ...

Activate an asynchronous request within a dropdown menu that was loaded using ajax

Let me start by presenting a simplified version of my code: HTML : <form id="add"> <select id="cat"> <option selected value="">…</option> <option value="a">A</option> <option value="b"& ...

Typescript disregarding conditional statements

Looking for some assistance with a Next.JS React-Typescript application Here's my code snippet for handling the video HTML element const videoRef = useRef<HTMLVideoElement>(); useEffect(() => { videoRef !== undefined ? videoRef.current. ...