'Importing "@terra-money/terra.js" throws Uncaught TypeError (Failed to resolve module specifier)

I want to work with this sample code from the Terra.js repo that I put in a file called terra-test.js:

import { LCDClient, Coin } from '@terra-money/terra.js';

// connect to bombay testnet
const terra = new LCDClient({
  URL: 'https://bombay-lcd.terra.dev',
  chainID: 'bombay-12',
});

// To use LocalTerra
// const terra = new LCDClient({
//   URL: 'http://localhost:1317',
//   chainID: 'localterra'
// });

// get the current swap rate from 1 TerraUSD to TerraKRW
const offerCoin = new Coin('uusd', '1000000');
terra.market.swapRate(offerCoin, 'ukrw').then(c => {
  console.log(`${offerCoin.toString()} can be swapped for ${c.toString()}`);
});

But when I want to call the script functions via index.html

<html>
<head>
<title>Terra.js Test</title>
</head>
<body>
<script type="module" src="terra-test.js"></script>
</body>
</html>

... I get this error:

Uncaught TypeError: Failed to resolve module specifier "@terra-money/terra.js". Relative references must start with either "/", "./", or "../".

Can somebody point me in the right direction? Thanks a lot!



Solution 1:[1]

If you just want to get experience with the TerraJS example you shared then run it from the command line with NodeJS (after npm installing the modules of course)

There are many challenges in the history of the “latest” JavaScript running in the browser versus NodeJS running JavaScript from command line or as a server. The largest challenge is modules, imports, dependencies and packaging.

All user interface examples I’ve worked using TerraJS have used React and the create-react-app or even NextJS. Which use Babel and Webpack to package Node Modules to work in the browser (ex. working from index.html, especially when there are dependencies on dependencies in the module). Off topic but related, I have recently been trying to work with another project (not Terra related) that was done with browserfy which is yet another earlier project to try to help with packaging modules and allow them to work in the browser.

My advice would be to embrace React for your TerraJS frontend and user interface development. And embrace NodeJS for just working with TerraJS Library directly.

Solution 2:[2]

Have you installed the module through npm package manager? npm install @terra-money/terra.js

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 petegordon
Solution 2 xcsob