Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
57
rated 0 times [  63] [ 6]  / answers: 1 / hits: 5311  / 4 Years ago, fri, january 17, 2020, 12:00:00

I'm an absolute beginner to TypeScript. In my first hello world project I got completely confused with typescript modules.
I'm trying to use Axios to get some data from a fake json api but the problem is that my IDE isn't able to find Axios from node modules.
Things that i've done so far.



1- First I made index.ts file



import axios from axios;
const url = https://jsonplaceholder.typicode.com/users/2;

axios.get(url).then(response => {
console.log(response.data);
});


2- Then I installed axios via npm which created the node-modules folder



npm install axios


3- I got the api result by this command in cmd



ts-node index.ts


This is compiled js



use strict;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { default: mod };
};
Object.defineProperty(exports, __esModule, { value: true });
var axios_1 = __importDefault(require(axios));
var url = https://jsonplaceholder.typicode.com/users/2;
axios_1.default.get(url).then(function (response) {
console.log(response.data);
});


so far everything is good and data is shown in cmd. but everything is different in browsers(Chrome, Firefox and Edge). When I link compiled js to my browser I get this error




Uncaught ReferenceError: exports is not defined




I found that i have to change settings in tsconfig file from commonjs to requirejs but when i change the module: commonjs, to module: amd, import axios from axios; turnes red in index.ts file and IDE alerts me that cant find axios. what I'm missing here??



I searched many websites including stackoverflow but did not find any good answer. If u need more information I mean my package,json or anything pls comment so I'll add them to this question


More From » typescript

 Answers
5

Because browser doesn't recognize the commonjs output, and failed to find the axios source code.



Typescript only compile the ts code into js, but not responsible for generating bundle file. To run your code in browser, you have to use a bundler like webpack to transform the commonjs output into a bundle file which includes all source codes.



You can follow the webpack docs to setup the webpack with typescript


[#5021] Wednesday, January 15, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
manuel

Total Points: 747
Total Questions: 96
Total Answers: 95

Location: Argentina
Member since Thu, Mar 18, 2021
3 Years ago
manuel questions
Sat, Mar 28, 20, 00:00, 4 Years ago
Sun, Jun 30, 19, 00:00, 5 Years ago
Sat, Jun 15, 19, 00:00, 5 Years ago
Sat, Feb 9, 19, 00:00, 5 Years ago
;