Webpack encountered a ModuleNotFound Exception while running Typescript

This inquiry pertains to webpack, TypeScript, and npm. Here is my folder structure:

.
-src
--apps
---TemplateInvestigate    
   Main.ts
-node_modules 
--parse-json 
   index.js
---vendor    
   parse.js    
   unicode.js

In the Main.ts file within TemplateInvestage, I am attempting to import a JSON parser like so:

import * as a from "../../../node_modules/parse-json/index.js";

My Webpack configuration is as follows:

var ES5to3OutputPlugin = require("es5to3-webpack-plugin");
module.exports = {  
  entry: {

      'TemplateInvestigate':"./src/apps/TemplateInvestigate/Main.ts"
  },

  output: {
    filename: './dist/[name].jsx'
  },
  resolve: {
    extensions: [   '.ts']
  },
  module: {
    loaders: [
      { test: /\.ts$/, loader: 'ts-loader' }
    ]
  }
  ,plugins : [
    new ES5to3OutputPlugin()
  ]
}

tsConfig setup:

 "compilerOptions": {
 //   "module": "commonjs",
     "noImplicitAny": false
  ,  "noEmitOnError": true
   , "removeComments": false
   ,"moduleResolution": "node"
   ,"allowJs" : true
   ,"baseUrl": "."
  }



}

When running webpack, I encountered the following error message:

ModuleNotFoundError: Module not found: Error: Can't resolve './vendor/parse'
in 'K:\projectFolder\node_modules\parse-json'
...

Please note that there is no type definition file available for the parse-json package that was installed via npm.

Answer №1

One issue arises with the parse-json module in JavaScript, as it is commonly imported using a statement like ./vendor/parse, which automatically resolves to ./vendor/parse.js by Node. However, in your webpack configuration, you have only set it to resolve .ts extensions. To solve this problem, you need to include .js in the resolve.extension array:

resolve: {
  extensions: ['.ts', '.js']
},

In addition, when importing modules from npm packages, it's recommended not to specify the full relative path but simply use the package name, as shown below (with a more descriptive variable name than a):

import * as parseJson from "parse-json";

Essentially, if you are not using a relative path for the import, the search will be within the node_modules directory (in the current and parent directories), eventually reaching the top level directory of your project where the parse-json module resides in node_modules. Also, there's no need to specify importing from index.js within parse-json/index.js, as the module itself defines an entry point that gets used upon importing – in this case, it's index.js.

To delve deeper into module resolution, refer to: https://nodejs.org/api/modules.html#modules_loading_from_node_modules_folders

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

Navigating additional information in D3 Node Link Force diagram

Recently delving into the world of D3, I have been pleasantly surprised by its capabilities and decided to experiment with the Directional Force Layout. My Objective Initially, I successfully created a json object using a for loop to prepare my items for ...

Error message on Android Web Console: ReferenceError - Worker object is not defined

As someone who is new to javascript, I have been struggling to understand why popular browsers seem to handle the definition "new Worker("BarcodeWorker.js")" differently than Android WebView. The original code for this Barcode Reader is from Eddie Larsso ...

Is there a way to adjust the dimensions of the circles?

I came across a code that I wanted to customize by changing the size of the circles. Would it be best to do this using JavaScript or CSS? Is there a way to achieve this modification? The complete code can be found at: https://codepen.io/XTn-25/pen/NWqeBaz ...

retaining the scroll position of a window when refreshing a div

There's this issue that's been bothering me lately. I update the database via an ajax call, refresh the div, everything works fine, but it still scrolls to the top of the page. Here's what I have attempted: function postdislike(pid, user, ...

tool for uploading and validating multiple file types

I have a file upload control for uploading multiple files. Here is an example: <ajaxToolkit:AsyncFileUpload ClientIDMode="Static" name="aa[]" BackColor="Azure" ForeColor="Black" OnClientUploadError="uploadError" OnClientUploadStarted="abc" ...

Obtaining image urls from RSS feeds

I've been attempting to extract image URLs from various news RSS feeds such as Despite using the rss-parser library, I find that the documentation and examples mostly focus on other elements instead of media content and images. Is there a reliable me ...

Displaying the Laravel modal again with the identical data upon encountering a validation error

I have a table displaying data from a database where each row contains a button that opens a modal with the current clicked row id. Here is an example of the code: <tbody> @foreach($receivedShipments as $shipment) <tr> ...

Transforming a jQuery snippet to display an additional element

I am currently implementing a code that displays a "follow me" box on the left side of my website. My goal is to add a second button right below this one, which will redirect users who click it to an RSS link. Any suggestions on how I can achieve this? ...

Error encountered: index.html:17 - An InvalidStateError was thrown when attempting to execute the 'send' function on the XMLHttpRequest object. The object's state must be OPENED in order to send the Ajax request

When attempting to run index.html on a local host with xampp, an error is encountered: index.html:17 Uncaught InvalidStateError: Failed to execute 'send' on 'XMLHttpRequest': The object's state must be OPENED.sendAjax @ index.html: ...

Vue- async function results in a Promise object with a status of <pending>

Hey everyone, I could use some assistance with my Vue code. Here's the issue: I'm attempting to retrieve data (specifically anime) from an online anime API. In my project, I have two files: Anime.vue (the view page) and getAnime.js (which house ...

What are the steps for retrieving a JSON object within an array?

var jsonData = '[{"type":"product","id":1,"label":"Size","placeholder":"Select Size","description":"","defaultValue" :{"text":"Size30","price":"20"},"choices":[{"text":"Size30","price":"20","isSelected":"true"},{"text" :"Size32","price":"22","isSelec ...

Performing mathematical calculations using javascript

In my project, I'm utilizing HTML, CSS, and JavaScript to achieve the following: Dropdown menu for Category (Coffee Appliance) Dropdown menu for Product (Keurig Coffee Maker) Wattage: 1500kWh (auto-filled from Local Storage) Daily Energy Con ...

Add a variety of input values to a div in designated spots

Objective: The aim is to allow the user to connect form fields with specific locations within a content from another div, and then add the text entered in individual input fields to those corresponding locations. Here is the link to the fiddle HTML: < ...

Exploring the compatibility of Angular.js with iframes in Firefox

For some reason, I can't seem to get iframes to work properly in Firefox when using Angular.js routes. It's probably something simple that I'm missing, but I just can't figure it out. If you want to take a look at the code, here is a ...

Tips for sending a parameter within a JavaScript confirm method?

I currently have the following code snippet in my file: <?php foreach($clients as $client): ?> <tr class="tableContent"> <td onclick="location.href='<?php echo site_url('clients/edit/'.$client->id ) ?>&ap ...

PHP - Dynamically load a div element with filtering options once both date fields are populated

I recently created a leave request form using PHP, Javascript, and CSS. I would like to implement a feature where if the user selects the same date in two different date fields, a new section will appear with two radio buttons for choosing between half d ...

Retrieve the text and image simultaneously using jQuery

I need to retrieve either text or image within a modal. Use textCont to retrieve text. The content within a div can be either text or image. It will retrieve whatever is present there. Below is the JavaScript code for text retrieval. var contId = 0; var ...

Leveraging the 'window' object as a dependency in the useEffect hook within NextJS

I'm encountering an issue where I need a function to run when the type of window.performance.getEntriesByType("navigation")[0].type changes. I attempted to use useEffect for this purpose, but it resulted in a 'window is not defined&apos ...

Uniting the client-side jQuery and server-side Express for enhanced functionality

Currently, I am deepening my understanding of Express/Node. My goal is to construct a basic HTML form that undergoes client-side validation (using jQuery/AJAX) while also being processed server-side (via Express.js). The application's complexity remai ...

The Express.io platform is having trouble loading the JavaScript file

Currently, I have an operational Express.io server up and running. However, I am encountering issues with the proper loading of my Javascript files. Here is a snippet from my Jade file: html head h1 Test index body script(src="/so ...