Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does ES6 import/export need ".js" extension?

I installed chrome beta - Version 60.0.3112.24 (Official Build) beta (64-bit)

In chrome://flags/ I enabled 'Experimental Web Platform features' (see https://jakearchibald.com/2017/es-modules-in-browsers)

I then tried:

<script type="module" src='bla/src/index.js'></script> 

where index.js has a line like:

export { default as drawImage } from './drawImage'; 

This refer to an existing file drawImage.js

what I get in the console is error in

GET http://localhost/bla/src/drawImage  

If I change the export and add ".js" extension it works fine.

Is this a chrome bug or does ES6 demands the extension in this case ?

Also webpack builds it fine without the extension !

like image 466
kofifus Avatar asked Jun 11 '17 08:06

kofifus


People also ask

Do you need .JS for import?

One of the major differences between require() and import() is that require() can be called from anywhere inside the program whereas import() cannot be called conditionally, it always runs at the beginning of the file. To use the require() statement, a module must be saved with . js extension as opposed to .

Does ES6 import Export?

With the help of ES6, we can create modules in JavaScript. In a module, there can be classes, functions, variables, and objects as well. To make all these available in another file, we can use export and import. The export and import are the keywords used for exporting and importing one or more members in a module.


2 Answers

The extension is part of the filename. You have to put it in.

As proof of this, please try the following:

  • rename file to drawImage.test
  • edit index.js to contain './drawImage.test'

Reload, and you'll see the extension js or test will be completely arbitrary, as long as you specify it in the export.

Obviously, after the test revert to the correct/better js extension.

like image 179
pid Avatar answered Sep 16 '22 15:09

pid


No, modules don't care about extensions. It just needs to be a name that resolves to a source file.

In your case, http://localhost/bla/src/drawImage is not a file while http://localhost/bla/src/drawImage.js is, so that's where there error comes from. You can either add the .js in all your import statements, or configure your server to ignore the extension, for example. Webpack does the same. A browser doesn't, because it's not allowed to rewrite urls arbitrarily.

like image 39
Bergi Avatar answered Sep 16 '22 15:09

Bergi