Error occurred: Unable to locate module: Error: Unable to resolve './templates'

Currently, I am working on a TypeScript file named index.ts which includes some JavaScript code. The main functionality involves importing Bootstrap CSS and templates.

import 
'../node_modules/bootstrap/dist/css/bootstrap.min.css';
import 'bootstrap';
import * as templates from './templates';

document.body.innerHTML = templates.main;

const mainElement = document.body.querySelector('.b4.main');
const alertsElement = document.body.querySelector('.b4-alerts');

mainElement.innerHTML = templates.welcome;
alertsElement.innerHTML = templates.alert;

However, when running my project using webpack dev server, an error occurs:

Module not found: Error: Can't resolve './templates' in '/Users/BorisGrunwald/Desktop/Node/b4-app/app'

Even though both files (index.ts and templates.ts) are located in the same folder, the system fails to locate "templates.ts."

Displayed below is a snapshot illustrating the structure of my project:

https://i.sstatic.net/hHdWK.png

For reference, included here is a snippet of my webpack configuration:

'use strict';

const path = require('path');
const distDir = path.resolve(__dirname,'dist');

const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');

 module.exports = {
    entry: './app/index.ts',
    output: {
        filename: 'bundle.js',
        path: distDir
    },
    devServer: {
        contentBase:distDir,
        port:60800
    },
    plugins: [
        new HtmlWebpackPlugin({
            title: 'Better Book Bundle Builder'
        }),
        new webpack.ProvidePlugin({
            $:'jquery',
            jQuery:'jquery'
        })
    ],
    module: {
        rules: [{
            test:/\.ts$/,
            loader:'ts-loader'
        },{
            test: /\.css$/,
            use:['style-loader','css-loader']
        },{
            test: /\.(png|woff|woff2|eot|ttf|svg)$/,
            loader:'url-loader?limit=100000'
        }]
    }
};

The contents of templates.ts are as follows:

export const main = `
    <div class="container">
        <h1>B4 - Book Bundler</h1>
        <div class="b4-alerts"></div>
        <div class="b4-main"></div>
    </div>
`;

export const welcome = `
    <div class="jumbotron">
        <h1>Welcome!</h1>
        <p>B4 is an application for creating book bndles</p>
    </div>
`;

export const alert = `
    <div class="alert alert-success alert-dismissible fade in" 
role="alert">
        <button class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
        <strong>Success!</strong> Bootstrap is working
    </div>
`; 

If anyone can identify what might be causing the issue, your insights would be greatly appreciated!

Answer №1

Test to see if this solution works. It enables importing from a directory without needing to use periods.

import {main, welcome, alert} from './templates';

By default, Webpack does not recognize .ts files. You can update resolve.extensions to include .ts. Make sure to include the usual extensions too, as most modules depend on the automatic use of the .js extension.

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

This rule also applies to other types of files, such as .scss files. If not included, you may encounter an error like

SassError: Can't find stylesheet to import.

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

jQuery's Multi-Category Filter feature allows users to filter content

I have been working on creating a filter function for my product list. The idea is that when one or more attributes are selected, it should fade out the elements that do not match. And then, if a filter is removed, those faded-out items should fade back in ...

Is there a way to transfer a value from one JS function to another in Node.js?

I am struggling to retrieve the return value from a JavaScript function in Node.js and pass it back in a POST method within my server file. Despite my efforts, I keep receiving an undefined result. What could be causing this issue? My objective is to retur ...

One way to display a table is by populating it with data from an API. If the table does

Within my Angular 6 application, there exists a table that displays data fetched from a web api. Additionally, I have incorporated some ngIf containers. One of these containers is programmed to exhibit a message in case the web api data turns out to be emp ...

Transforming unprocessed string information with a set position-dependent format into a structured format such as JSON

Here is the scenario I am dealing with: The input format consists of a string with a fixed total length, where each set of fixed positions represents a different value. For example, if the input is "ABCDE12345", position 1 to 3 ("ABC" ...

Activating gzip compression using fetch.js

I am utilizing fetch.js (https://github.com/github/fetch) to transmit a rather substantial JSON object to the backend. The size of the JSON is significant due to it containing an SVG image string. My question is whether fetch.js applies gzip compression a ...

What is the best way to delete a single asterisk from the content of an HTML <td> element?

Looking for a way to remove or replace an asterisk from the inner content of a <td> element. I have a block which includes some text and an input field. For this example, let's say <td> == this $(this)[0].innerHTML "*&nbsp;<input ...

Securing pathways in Next.js using middleware and Next-Auth

Hey there, I'm currently working on adding some route protection in NextJS using middleware for authentication with next-auth. According to the documentation, this is what my middleware.ts file should look like: export { default } from "next-auth ...

"Displaying an array using React Hooks' useState causes the content to

I want to enhance my image uploading functionality in useState by implementing a specific function. Once the images are uploaded, I need to render them on the page. However, I am facing an issue with rendering the returned array. Here is the current code ...

Limit the elements in an array within a specified range of dates

Currently, I am working on implementing a filter functionality for a data array used in a LineChart within my Angular application using TypeScript. The structure of the data array is as follows: var multi = [ { "name": "test1", "series": [ ...

Fetching information with request query parameters in Node.js

Working on implementing email verification using nodemailer for user sign-ups. The process involves sending out an email containing a link (usually something like localhost:3000/verify/?id=##). After the user clicks the link, I can see that a GET request ...

Jasmine test failing due to uninitialized angular controller

I encountered some difficulties while writing jasmine tests for an AngularJS application that utilizes angular ui-router. Despite proper initialization of my services and app in the test, I found that the controllers were not starting up correctly. In an e ...

Retrieving and securely storing information using fetch() on authenticated REST services

Currently, I have successfully set up a React application that communicates with a REST backend which is built using Python and Flask. The specific functionality I have achieved involves downloading data from a database and saving it as a CSV file through ...

Why is my custom function failing to operate on an array?

My function is created to organize and remove duplicates from a provided array. Below is an excerpt of the code: Bubble Sort - function organize(postsCollection, type, direction){ let target = postsCollection[0][type]; let swapp = false, ...

The .load() function seems to have a problem with my slider widget

I am facing an issue with a slider on my page that displays posts from a specific category. When the user clicks on "next category", the content slides to the left and new content is loaded along with its respective slider. The problem arises when the loa ...

Need help with resetting a value in an array when a button is clicked?

Using Tabulator to create a table, where clicking on a cell pushes the cell values to an array with initial value of '0'. The goal is to add a reset button that sets the values back to '0' when clicked. component.ts names = [{name: f ...

Querying Techniques: Adding an Element After Another

CSS <div id="x"> <div id="y"></div> <div> <p>Insert me after #y</p> The task at hand is to place the p tag after '#y', and whenever this insertion occurs again, simply update the existing p tag instead of ...

Angular applications encountering issues with Express delete-route functionality

For some reason, I am having trouble with Delete routes in my Angular applications. They seem to work perfectly when tested using Postman, but fail to function when called from within the Angular app. //Attempting to call a delete route from an Angular app ...

What is the method for retrieving a value using the Angular forEach function?

I'm encountering an issue with retrieving values from an angular forEach loop. Below is the data I am working with: vm.memberDetails={ "member": [ { "firstName": "HARRY UTTWO", "lastName": "POTTER", } ...

Binding an ID to an <ion-textarea> in Ionic 3

Can an ID be assigned to an ion-textarea? For example: <ion-textarea placeholder="Enter your thoughts" id="thoughtsBox"></ion-textarea> Thank you very much ...

What is the best way to execute useEffect in React Router?

Struggling to get my useEffect function to run properly in a React app using a REST API for a Inventory Management application. The issue seems to be with setting the item variable. Any insights on why this might be happening? Item.jsx: import React, { us ...