"Error: imports are undefined" in the template for HTML5 boilerplate

After setting up an HTML5 Boilerplate project in WebStorm, I navigate to the localhost:8080/myproject/src URL to run it. Within the src folder, there is a js directory structured like this:

libraries
models
    place.model.ts
      place.model.js
    address.model.ts
      address.model.ts
main.ts
  main.js

The Typescript compiler converts the .ts files to .js

Within my .model.ts files, I have defined a class as follows:

export class MyClass {
    x: string;
    constructor(x: string) {
        this.x = x;
    }
}

In my main.ts file, I import the class like so:

import {MyClass as My} from "./models/myclass.model";

However, upon attempting to access the URL, I encounter the error:

Uncaught ReferenceError: exports is not defined
. Upon inspecting the compiled main.js file, I notice the following line added:

Object.defineProperty(exports, "__esModule", { value: true });

I attempted to resolve this by adding the script below to my index.html file:

<script>var exports = {};</script>

This action resulted in a new error message:

ReferenceError: require is not defined
.

What could be missing in my setup and how can I rectify it?

UPDATE Initially, the project lacked a tsconfig file, which I manually included with the following content:

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es5",
    "sourceMap": false
  },
  "exclude": [
    "node_modules"
  ]
}

An attempt was made without "module": "commonjs", but unfortunately, it did not solve the issue.

Answer №1

After my initial attempt at using Webpack failed due to outdated configuration, I made the necessary changes and got everything up and running smoothly. I also managed to set up a watcher for detecting changes in .ts files.

const path = require('path');

module.exports = {
  entry: './src/js/main',
  mode: 'development',
  watch: true,
  watchOptions: {
    aggregateTimeout: 600,
    poll: 1000,
    ignored: /node_modules/
  },
  module: {
    rules: [
      {
        test: /\.ts$/,
        loader: 'ts-loader'
      }
    ]
  },
  resolve: {
    extensions: ['.webpack.js', '.web.js', '.ts', '.js', '.tsx', '.json']
  },
  output: {
    filename: 'main.js',
    path: path.resolve(__dirname, './src/js')
  }
}

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

Typescript error: Import statement not allowed here

Recently delving into the world of TypeScript, I encountered an issue when attempting to build for production. My first step was running tsc Although this step passed without any errors, I faced import errors when trying to execute the build file with ...

Retrieve an element generated by a React script without using the ref attribute

There is a chat button on my website generated by a script (zendesk chat) that creates an iframe with the ID "launcher". I am using Nextjs and I am trying to access this element, but I am unable to attach a ref since I do not have the code. I have been sea ...

Understanding the process of unmarshalling an array within a POST request

I am attempting to send an array of JSON data with a POST request to an API server. However, I keep encountering the following error: cannot unmarshal array into Go value of type models.UserRequest Despite trying to unmarshal the data using a factory and ...

Struggling to establish a default value for an AngularJS select dropdown

I'm diving into the world of AngularJS and facing a challenge with setting a default value on a select box. I've successfully listed objects in the select box and binding it to the model works seamlessly. However, as soon as I introduce a default ...

Controller encounters a error when requiring a module

Struggling to set up Stripe for my app, I've encountered some issues with the module implementation. Typically, I would require a module at the top of the file to use it. However, in the paymentCtrl file, when I do this, it doesn't work and I rec ...

Implement a feature that adds a circle element when an image is clicked in a React application

I am attempting to create a program that allows users to add circles to an image by clicking on it. Essentially, when the user clicks at coordinates (x,y), a circle with a radius of 10 will appear at that location. I am exploring ways to implement meta-pro ...

Obtain a collection of data- attribute values using jQuery

I am attempting to extract all the values from the data-hiringurl attributes found on this particular page . When I used var data = $("li").attr('data-hiringurl'); and var data = $("li").data('hiringurl'); in the console, an error mess ...

The URL is not being updated despite changes in document.location hash

I have created a script that toggles (show/hide) between different DIVs on the page (highlighted below in the various boxes =). However, I am facing an issue with updating the URL string when switching between different DIVs. For instance, if I navigate t ...

Improving User Experience with HTML Form Currency Field: Automatically Formatting Currency to 2 Decimal Places and Setting Maximum Length

Hello there, I am currently facing an issue with the currency auto-formatting in a deposit field on my form. The formatting adds 2 decimal places (for example, when a user types 2500, the field displays 25.00). However, the script I wrote does not seem to ...

Unable to get i18next functioning in my Node.js Express backend

I'm currently facing difficulties in implementing localization for my nodeJS backend. Within my Angular frontend, I have a language-setting interceptor that successfully sets the language in the request header. You can refer to the image below which ...

How Python Flask sends a string as &#34 to an HTML page

I am working on a Flask app and I need to send simple JSON data from the app.py file to an HTML page. Here is the relevant code in my app.py: jsonArr = [{"type": "circle", "label": "New York"}, {"type": "circle", "label": "New York"}] return ...

Having trouble resolving a missing dependency warning with the useEffect React Hook in my Next.js app. Any tips on how to fix this

Currently, I'm facing the following warning: Warning: React Hook useEffect has a missing dependency: 'router'. Either include it or remove the dependency array Here is the code snippet from _app.js that seems to be causing this issue: cons ...

The Failure of window.pushState in HTML 5 History

Looking to implement ajax loading for updating center content and URL without refreshing the page. Everything seems to be working fine except for the history management. It appears that window.pushState is not properly recording URLs or the popstate even ...

Transform an HTML table string into JSON format

I discovered a useful library called table to JSON that allows me to convert an HTML Table to JSON using its ID (#testtable in the example below): var table = $('#testtable').tableToJSON(); alert(JSON.stringify(table)); However, I am interested ...

What is the best way to pass default event argument alongside another argument in React?

This snippet demonstrates the function I wish to call when a certain input type is invoked: _handleOnEnterPress = (e, receiverUserId) => { if (e.keyCode === 13) { // assuming keycode 13 corresponds to 'enter' console.log("pressed ...

Encountering a TypeError message stating that "selector.includes is not a function" while attempting to scrape using cheerio and

Trying my hand at web scraping with the code snippet below: const cheerio = require('cheerio'); const jsonframe = require('jsonframe-cheerio'); const $ = cheerio.load('https://coinmarketcap.com/all/views/all/'); jsonframe($) ...

What is the best way to show the user's name on every page of my website?

I'm facing an issue where I can successfully capture the username on the home page using ejs after a login, but when transitioning to other pages from the home page, the username is no longer visible. It seems like I am missing some logic on how to ha ...

Tips for crafting paragraphs that double as sieves

I'm trying to simplify and shorten this code. I have three HTML paragraphs acting as filters: "all", "positive," and "negative", referring to reviews. Each has a corresponding div for reviews: "allcont", "poscont", and "negcont". Clicking on any of th ...

What is the process for adjusting the form transition?

I am currently working on a form that has a transition effect However, I encountered an issue: check out the problem here My goal is to keep the magnifying glass fixed in place while the form moves Here is a snippet of my code: import Search fro ...

The useState variable remains unchanged even after being updated in useEffect due to the event

Currently, I am facing an issue in updating a stateful variable cameraPosition using TypeScript, React, and Babylon.js. Below is the code snippet: const camera = scene?.cameras[0]; const prevPositionRef = useRef<Nullable<Vector3>>(null); ...