Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to es6 import a commonjs module?

I have a commonjs module, which was generated by Typescript 3.3.3.

Is it possible to use it with an es6 import statement? Here's what I have tried.

The generated module exports CountUp like this at the end of the file:

exports.CountUp = CountUp;

In my main.js:

import { CountUp } from './js/countUp.js';

And in index.html:

  <script src="./js/countUp.js"></script>
  <script src="./main.js" type="module"></script>

But I get

countUp.js:13 Uncaught ReferenceError: exports is not defined at countUp.js:13

(Note: countUp.js is now distributed as an es6 module)

like image 900
inorganik Avatar asked Mar 14 '19 16:03

inorganik


1 Answers

Short Answer: No


When using es6, you need to export using export and not exports. exports is a commonjs feature primarily used within node and not a web browser.

If you would like to use commonjs you need to use a third party library like requirejs, but this uses require() and not import, and exports and not export. You will then be able to write your code using import/export with typescript but it will be compiled using require and requirejs will handle the rest.

So, to use it in the browser properly, you would do it like so:

test.js

export function Test() {
  console.log('hello')
}

index.js

import { Test } from './test.js'
Test()

Then when you load the file in your html, the function test will execute.

<script src="index.js" type="module"></script>
like image 82
Get Off My Lawn Avatar answered Oct 19 '22 17:10

Get Off My Lawn