External node modules written in TypeScript can occasionally be transpiled into both `module.exports` and `

Currently, I am in the process of transforming my node application to utilize TypeScript external modules. While everything runs smoothly when executing the app, I encountered an issue with my mocha tests "exploding" after converting some of my .ts files due to a

SyntaxError: Unexpected reserved word
.

After extensive troubleshooting, I discovered a reproducible failure scenario. I have a straightforward autoRoles.ts file that defines the user roles available. Before implementing external modules, it appeared as follows:

/// <reference path="../../typings/backend_typings.d.ts" />

module.exports.roles = {
  // role definitions
}

Now, post-conversion:

/// <reference path="../../typings/backend_typings.d.ts" />

export let roles = {
  // role definitions
}

Upon running the mocha tests, the following error is generated:

>> Mocha exploded!
>> SyntaxError: Unexpected reserved word
... (additional error details)

I can switch between the old and new implementations for the autoRoles.ts file resulting in mocha passing or failing, respectively. Line 77 of userRoles.ts contains a require('<path>/autoRoles').

When comparing the transpiled versions, the only discrepancy lies in the usage of 'module.exports' in the old version and just 'exports' in the new one.

Old:

/// <reference path="../../typings/backend_typings.d.ts" />
exports.roles = {
  // role definitions
}

New:

/// <reference path="../../typings/backend_typings.d.ts" />
module.exports.roles = {
  // role definitions
}

Despite being aware that "exports" is simply a shorthand for "module.exports", the reason behind this causing mocha failures eludes me. It's puzzling why merely switching between the two versions without any other alterations leads to mocha "exploding." Additionally, I've observed that tsc occasionally uses "module.exports" while other times opting for "exports" in transpiled modules. The inconsistency raises questions - why are these discrepancies present and more importantly, what triggers mocha to explode?

Answer №1

Encountered unexpected reserved word

To resolve this issue, make sure to include "use strict"; at the beginning of your file. It is possible that you are using a variable name that is a reserved keyword. For more information on strict mode and avoiding reserved keywords, refer to this documentation. TypeScript will also provide warnings for such variable names if the strict mode header is present in the file.

The error is not related to module.exports.roles = {...}.

I have observed that transpiled modules may sometimes use "module.exports" and other times use "exports".

This behavior is consistent with the nodejs convention, optimizing for parsing efficiency by reducing the number of characters (bytes) needed at runtime.

export let foo = 123;

Translates to

exports.foo = 123;

(since exports == module.export, therefore exports.foo == module.export.foo ... as you already know). However, in the case of:

let foo = 123;
export = foo;

It results in

var foo = 123;
module.exports = foo;

Because reassigning exports with exports = foo would mean module.export !== exports. Therefore, exports should be used for extension purposes only, not for assignment.

Answer №2

After extensive debugging, I discovered that mocha was not utilizing the transpiled .js source code files generated by tsc. It seemed to be attempting to execute the "export var roles" function from the .ts file, where 'export' is a reserved word.

I stumbled upon this informative post, which hinted at mocha performing its own transpiling. The suggestion was to use "typescript-require", but it seems that this package is in the process of being replaced by "ts-node". As a result, I updated my grunt-ts configuration as follows:

mochaTest: {
    test: {
        options: {
            reporter: 'spec',
            require: [
                'ts-node/register'
            ]
        },
        src: ['lib/test/**/*.spec.js']
    }
},

This solution worked well for me, though I would appreciate any insights into what exactly mocha was doing behind the scenes. Furthermore, I am curious as to why mocha was able to handle transpiling and did not detect the "reserved word" issue in other .ts files using export statements.

Edit 10/30/2015:

I eventually realized why mocha was attempting to run my .ts files. I had mistakenly imported some of them with require('/path/file.ts') instead of omitting the '.ts' extension. Consequently, I no longer required 'ts-node' in my mocha runner. This oversight also clarified why mocha was only causing errors in certain .ts files.

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

Passing an observable from parameters to a pipe in RxJS: A guide

Can someone help me with writing a TypeScript function like the one below: function abc(arg1, arg2, arg3) { pipe(arg1, arg2, arg3...); // or someSubject.pipe(arg1, arg2, arg3..) } I keep getting errors when trying to build the code. How can I success ...

Struggling to properly import the debounce function in ReactJS when using TypeScript

I am facing an issue while trying to properly import the debounce library into my react + typescript project. Here are the steps I have taken: npm install debounce --save typings install dt~debounce --save --global In my file, I import debounce as: impo ...

Tips for resolving the issue of dropdown menus not closing when clicking outside of them

I am currently working on an angular 5 project where the homepage consists of several components. One of the components, navbarComponent, includes a dropdown list feature. I want this dropdown list to automatically close when clicked outside of it. Here i ...

Adding a line break ( ) in a paragraph within a TypeScript file and then transferring it to HTML does not seem to be functioning properly

Angular Website Component: HTML file <content-section [text]="data"></content-section> TypeScript file data = `Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's stand ...

What could be causing the ERROR TypeError in an Angular form where "_co.service.formData" is undefined?

My attempt to create a form in Angular 7 has resulted in an error message: ERROR TypeError: "_co.service.formData is undefined" Here is the HTML code for the component: <form (sumbit)="signUp(form)" autocomplete="off" #form="ngForm"> <div clas ...

Does the Loopback Model have an "exists" method that includes a where clause?

I am interested in querying the data using filters to check for existence. Does loopback support this method of querying? If so, could you provide some guidance? myModel.exists({where: {and: [{city: "London"}, {gender: "F"}]}}, function(err, bool){ if(bo ...

Generating code for submitting two things simultaneously in node.js involves utilizing asynchronous functions and handling multiple requests. By

I am working with node.js and I need to generate code for activity_code. The desired format for the code is like this: LA0000000001, LA0000000002, LA0000000003, and so on in sequential order. However, I have encountered an issue where when submitting 2 a ...

NgFor is designed to bind only to Iterables like Arrays

After exploring other questions related to the same error, I realized that my approach for retrieving data is unique. I am trying to fetch data from an API and display it on the page using Angular. The http request will return an array of projects. Below ...

Load certain database information into memory as Express initializes

Are there any efficient methods for storing data in Express? For instance, I am interested in preloading all API keys from a PostgreSQL database into memory when the server is initialized to avoid having to query the database for each API request. I consi ...

Error: Unable to access the 'create' property of an undefined object while utilizing sequelize to register a user and add an entry

Whenever I try to execute this controller, an issue arises indicating a problem with the recognition of the .create method from the model. What is the correct way to import Sequelize in order to utilize it effectively? const db = require("../Models/m_use ...

What is the best way to transfer information from df ~ to my webpage?

I'm currently working on a pie chart that visualizes the disk space usage on my Linux machine. I need help figuring out how to properly parse this data onto a microservice URL. Any assistance would be greatly appreciated. Here's what I have so f ...

Updating Button Color Based on Input Field Value in EJS

How can I change the color of a button in EJS when the input value changes? <div> <textarea name="mytextarea" id="inputcontent" cols="30" rows="3" style="margin-top: 10px; margin-bottom: 10px; f ...

There was an error parsing the data from the specified URL (http://localhost:8000/src/client/assets/data.json

Hey there, I'm a newcomer to Angular and I'm having trouble reading a JSON array from a file. Every time I try, it gives me a "failed to parse" error. Can someone please provide some guidance? Here is my folder structure: src --assets ---a ...

Following an update, the functioning of Visual Studio Tools for Apache Cordova ceases to operate accurately

Currently working on an ionic application using Visual Studio Tools for Apache Cordova, everything was going smoothly until I decided to update the Tools for Apache Cordova and TypeScript Tools for Visual Studio. Following the update, the Ripple emulator s ...

Exploring Typescript and Clean Architecture with an In-Memory Database/Repository

Currently, I am integrating clean architecture in my latest project and facing challenges with repositories, data sources, and terminology. My aim is to test my useCases using an in-memory repository as I am only concerned about the business logic at this ...

Transferring information via onSubmit from React to Node.js

In my React script, I have an onSubmit function that is triggered when the submit button is clicked: const handleSubmit = (event) => { event.preventDefault(); const form = event.target; const rawdata = new FormData(form); const data = { email: rawda ...

Tips for extracting dynamically loaded content from a website using Node.js and Selenium?

I'm currently encountering some challenges when trying to scrape a website that utilizes react for certain parts of its content, and I'm unsure about the reason behind my inability to extract the data. Below is the HTML structure of the website: ...

Verify the type of email domain (personal or corporate)

Here's an example: isPersonalEmail("<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c0aea1ada580a7ada1a9aceea3afad">[email protected]</a>") // true isPersonalEmail("<a href="/cdn-cgi/l/email- ...

Connecting Node.js and Express with MySQL database

Today is my first time working with Node (Express) js, and I'm attempting to connect to a MySQL database. Here is the code snippet I found for my app.js file. app.js var express = require('express'), mysql = require('mysql'); // ...

show additional worth on the console

Just starting out with JavaScript. Trying to display additional values in the console. Uncertain about how to access add-ons. Can anyone help me troubleshoot? Here is my code snippet below: https://jsfiddle.net/6f8upe80/ private sports: any = { ...