Does ES6 import/export need “.js” extension?

2020-02-06 05:51发布

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 !

2条回答
Bombasti
2楼-- · 2020-02-06 06:17

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 configure your server to ignore the extension, for example. Webpack does the same.

查看更多
女痞
3楼-- · 2020-02-06 06:37

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

As a proof try this:

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

Reload and you'll see the extendion js or test is completely arbirary, as long as you specify it in the export.

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

查看更多
登录 后发表回答