Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert typescript npm module import syntax to ECMA2015 module import syntax

I'm trying to use a third party library in a Typescript project (specifically, three). As a proof-of-concept, I'm trying to resolve all of my client code as modules (without transpiling to ES5 or bundling).

my project is setup like this:

cgi/app.js (compiled typescript file)
node_modules/@types
node_modules/three/build/three.module.js
src/app.ts
index.html
tsconfig.json
package.json

And in my index.html

<head>
    <script type="module" src="node_modules/three/build/three.module.js"></script>
    <script type="module" src="cgi/app.js"></script>
</head>

I'm trying to have typescript resolve the three.module.js file while also using the type declarations from @types/three. Normally, you would import the library with: import { Scene } from 'three' which gives me type support, but the compiled module doesn't have proper ES6 syntax. It needs to be import { Scene } from './path/to/three.js.

Unfortunately, typescript does not support doing this automatically yet. I can instead import the ES6 module directly (without using @types) but then I lose type support.

Post typescript compilation, is it possible to convert the module resolution from the node syntax to the ES6 syntax? (e.g. import { Scene } from 'three' is converted to import { Scene } from './three.js'?

Specifically, is it possible to leverage rollup to accomplish this?

like image 274
Nathan Lafferty Avatar asked May 23 '18 00:05

Nathan Lafferty


People also ask

How do I install TypeScript modules?

Assuming the project was created from create-react-native-app . Make sure the project is ejected by run yarn eject. run yarn add victory-native react-native-svg to install module.

Does TypeScript use CommonJS?

Yes, you can use it in a same manner that you would use it in Javascript. Typescript is superset of Javascript, all things possible in Javascript are also possible in Typescript.


1 Answers

This can be done using Rollup's paths configuration value.

E.g. in my app.ts file I have a standard npm-style-import:

import { somedependency } from my-dependency (where my-dependency is a node module, such as three.)

In the rollup.config file, you need to tell Rollup the path to this file:

output: { ... },
plugins: [ ... ]
paths: {'my-dependency': './your/web/path/to/the/dependency.js'}

Your compiled bundle will now have a good import to that code that can be understood by the browser.

like image 81
Nathan Lafferty Avatar answered Sep 21 '22 02:09

Nathan Lafferty