Avoid using the 'exports' keyword when compiling in Typescript

I recently started learning Typescript, although I am proficient in JS. My inquiry pertains to utilizing modules in TS for coding purposes and then excluding the modules when converting to JS.

In traditional JS, I segment functionalities into different files as follows:

//func.js
function add(a, b) {
    return a+b
}

//other.js
(function(){
    console.log(add(1, 2))
})

Assuming that func.js is loaded, this setup should function correctly.

However, working with TS introduces some interesting aspects:

//func.ts
export function add(a: number, b: number): number {
    return a+b
}

//other.ts
import { add } from "./func";

(function(){
    console.log(add(1, 2))
})

Upon compiling individual JS files, the output appears as:

//func.js
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function add(a, b) {
    return a + b;
}
exports.add = add;

//other.js
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var func_1 = require("./func");
(function () {
    console.log(func_1.add(1, 2));
});

This approach works well if browsers are compatible. Could there be a mistake in my implementation? My ultimate goal is to have TS code resembling plain JS without using modules, ensuring functions are present before execution.

Here's my tsconfig.json configuration:

{
  "compilerOptions": {
    "target": "ESNEXT",
    "lib": ["ES2015", "dom"],
    "module": "commonjs",
    "outDir": "js/",
    "rootDir": "ts/",

    "strictNullChecks": false,
    "baseUrl": "./",
    "esModuleInterop": true,

    "forceConsistentCasingInFileNames": true
  },
  "include": [
    "./ts/*"
  ]
}

Directory structure:

./js
./js/func.js
./js/other.js
./ts
./ts/func.ts
./ts/other.ts
./tsconfig.json

Edit: I'm utilizing JS in a browser environment, not Node. I aim to leverage TS advantages, except for modules. While modules are necessary to connect TS files, they must be excluded in the final JS (as many browsers do not support them). I desire the compiled JS code to discard module functionality.

Answer №1

I finally cracked the code on how to achieve the desired outcome.

Essentially, I realized that I was unnecessarily using import and export syntax. Setting "module": "none" accomplished what I needed, although I had to eliminate the import and exports from my code. After making these changes, everything compiled smoothly!

Answer №2

When dealing with modules, it's crucial to have a loader that can connect these modules together. Popular options include SystemJS ("system"), RequireJS ("requirejs"), and more. Prior to loading any scripts, you will need to load their corresponding libraries.

An alternative approach is to utilize the "umd" file format, which aims to be universal and compatible across various environments - even in browsers lacking specific libraries (it relies on global fall-backs, necessitating a particular order of loading).

Another option is to consolidate all your code into a single file using outFile, eliminating the need for a loader altogether.

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

Automatically convert TypeScript packages from another workspace in Turborepo with transpilation

I have set up a Turborepo-based monorepo with my primary TypeScript application named @myscope/tsapp. This application utilizes another TypeScript package within the same repository called @myscope/tspackage. For reference, you can view the example reposit ...

Top location for Cordova/Phonegap events in AngularJS

Currently, I am working on an AngularJS Cordova app and so far everything is progressing smoothly. My next objective is to integrate Cordova plugins into the application, specifically the Cordova Connect plugin, which will allow me to monitor network conne ...

The issue of undefined return for multiple columns in MVC when using MCAutocomplete Jquery UI

My MVC multiple column is returning undefined. What am I missing or what is wrong with my code? Please help. https://i.sstatic.net/euwe8.png Controller public ActionResult EmployeeIDSearch(string term) { // Get Tags from data ...

A guide on how to initiate a click event in Angular 5 using JQuery

I am trying to trigger a click event for each element based on its id, but it doesn't seem to be working. Below is the code I am using: ngOnInit() { this.getProductsLists(); } getProductsLists() { this.supplierService.getProductLists() .sub ...

In Vue.js, is it possible to nest a <tr> tag inside another <tr> tag?

I've been working on a dynamic table in vue.js, using the code snippet below: <template> <tr class="left-align" v-for="(item,index) in itemList" :key="index.id"> <td>{{item.items}}</td> ...

Learn how to dynamically adjust context using a server-client architecture with TRPC

Currently, I am referring to the tRPC documentation for guidance on creating a server side caller. But I'm facing a challenge in dynamically setting the value when incorporating it into my NextJS 13 pages. In my context.ts file, you will find the fol ...

When the page is reloaded, JavaScript code remains unprocessed

Within a mobile website, there is a JavaScript snippet that appears as follows: <script type="text/javascript"> (function() { // actual function code is not shown here }()); </script> Upon initial page load, the code is successfully execute ...

Avoiding a browser becoming frozen during an AJAX call

I'm currently working on sending a request when a user closes the page using the onbeforeunload event. This event triggers when the tab is closed or the page is refreshed. Here's my event implementation: window.onbeforeunload = function() { ...

Implementing folder-specific routing in Express js

I'm struggling to figure out how to implement a solution that functions like this code snippet. I need to serve different folders based on various parameters, but I'm hitting a roadblock. An example of this in action would be incredibly helpful. ...

Sending a Boolean value from a child component to its parent state in React JS

Within my application, I have implemented a login feature in the navbar component. However, I am encountering an issue with updating a variable in the main component upon successful login. Although I have successfully managed to set up the login functional ...

Command to conceal components for users visiting as guests

I'm looking to develop a directive that hides specific elements for guest users. Here is the current code I have: angular.module('someMod') .directive('premiumUser', premiumUser) .controller('PremiumUserCtrl', Pr ...

Sort through an array of objects by their respective values within another array of nested objects

I am struggling to filter out positions from the positions array that are already present in the people array. Despite trying different combinations of _.forEach and _.filter, I can't seem to solve it. console.log(position) var test = _.filter(posi ...

What steps are needed to convert the format to an array in JavaScript?

I have received a value in the format: [["first"],["second"],["third"]] However, I need it to be like this: {"first","second","third"} How can I achieve this using JavaScript? ...

Establishing updated file path for resources in JavaScript based on environment

I'm currently facing an issue with my external Javascript file that uses the getScript() function to execute another JS file. Both files are located on static.mydomain.com, as I am trying to set up a Content Delivery Network (CDN) for the first time. ...

Vue initialization encounters an issue with starting 'marker-animate-unobtrusive' package

I am encountering an issue with marker-animate-unobtrusive and keep receiving the following error: https://i.sstatic.net/Y69xK.png While browsing through SO, I came across a post discussing the importance of requiring the file after Google has loaded. Ho ...

Enhancing Your WordPress Menu with Customized Spans

I have a WordPress menu structured like this: <div id="my_custom_class"> <ul class="my_custom_class"> <li class="page_item"><a href="#">page_item</a> <ul class='children'> <li class="page_item chil ...

Clean coding techniques for toggling the visibility of elements in AngularJS

Hey everyone, I'm struggling with a common issue in my Angular projects: app.controller('indexController', function ($scope) { scope.hideWinkelContainer = true; scope.hideWinkelPaneel = true; scope.headerCart = false; scope. ...

divide an item according to its category

Hey guys, I need some help with a coding problem! So here's the object I'm working with: var x = {code0: "codefdg", mcode0: "mcodefdg", mcode1: "mcodefdg", comments1: "commentsfdg", code3: "fdg"…} I want to split this object into different pa ...

Error encountered during React application compilation due to SCSS loading issue

I've encountered an error while trying to develop a React application with Webpack. The issue seems to be related to the main SCSS file: ERROR in ./resources/scss/style.scss (./node_modules/css-loader/dist/cjs.js??ref--6-2!./node_modules/sass-loader/ ...

Using Vue to showcase the result of a form submission on a separate page

Working with a <form> in the context of vue has been successful as I am able to send the form data to the server, receive a JSON response, and print it on the console. However, my current challenge involves displaying this JSON response on a differe ...