简体   繁体   中英

Can't import ES6 module

I have problems, importing a module to my index.js file. When I start debugging, I always get the error "Uncaught SyntaxError: Unexpected identifier"

My index.html file:

.
.
.
</body>
<script type="text/javascript" src="js/jquery-3.3.1.min.js"></script>    
<script src="js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/defines.js"></script>
<script type="text/javascript" src="js/jgestures.js"></script>
<script type="text/javascript" src="js/mdb.js"></script>
<script type="module" src="index.js"></script>
<script type="module" src="js/global.js"></script>
</html>

The module I want to import "modals.js":

class Modals{
  let b = 0;
}
export {Modals};

First line of my index.js file (where the error occures):

import {Modals} from './modals.js'

Does anyone has an idea what's wrong with my code?

Looks like you are not using ES6 classes properly. Also, keep in mind not all browsers work with ES6, it might be better to use functions or a transpiler like Babel.

I'd recommend reviewing the docs to get a refresher, but here is a code snippet of what you'd need to do for your example to work with ES6 classes

Your modals.js file would become:

class Modals{
  constructor (b) {
    this.b = b;
  }
}
export {Modals};

Your index.js:

import {Modals} from './modals.js';

let m = new Modals('something')
console.log('m', m)

Your index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script type="module" src="index.js"></script>
</body>
</html>

Good luck!

I would suggest first to check the browser support. ES6 modules have been around for a while now but it may be the case that your browser version does not support this syntax.

Then, you would need a transpiler like Babel to use this type of statements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM