我试图在我的项目中运行一些ES6代码,但我得到了一个意外的令牌导出错误。

export class MyClass {
  constructor() {
    console.log("es6");
  }
}

当前回答

当我试图在我的项目中导入本地javascript模块时,我也得到了意外的令牌导出错误。当在index.html文件中添加脚本标记时,我通过将类型声明为模块来解决这个问题。

<script SRC = "。/path/to/the/module/" type = "module"></script> .

其他回答

在最新版本的Nodejs (v17?)中,您可以通过使用.mjs文件扩展名来使用顶级的“import”,“async”,“await”-而不是transpiling或变通方法。

   // > node my.mjs
   
   import {MyClass} from 'https://someurl'
   async func () {
     // return some promise
   }
   await func ()

对于那些在2022年看到这篇文章的人来说,我也犯了同样的错误,但我把代码改成了这样:

    module.exports = () => {
    getUsers: () => users;
    addUser: (user) => users.push(user);
  };

通常import不能在.js扩展名中工作,因为默认情况下js意味着javascript的cjs版本。如果你想要es6特性,你需要将.js扩展名重命名为.mjs扩展名

parent.mjs

export default class Car {
   constructor(brand) {
   this.carname = brand;
}
 present() {
   return 'I have a ' + this.carname;
  }
}

child.mjs

import Car from './parent.mjs'
export default class Model extends Car {
constructor(brand, mod , country) {
  super(brand);
  this.model = mod;
  this.country = country;
}
show() {
  return this.present() + ', it is a ' + this.model + "i am from " + 
  this.country;
  }
}

index . html

<!DOCTYPE html>
 <html lang="en" class="no-js">
  <head>
  <meta charset="utf-8">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, 
shrink-to-fit=no">
  <title>Quick Start Pack Template</title>
 </head>
 <div class="demo"></div>
 <script type="module">
   import Model from './child.mjs'
   let value = new Model("Ford", "Mustang", "bangladesh")
   document.querySelector(".demo").innerHTML = value.show()
 </script>
 </body>
 </html>

最后在活动服务器上运行此代码

要使用ES6,请添加babel-preset-env

在你的。babelrc中:

{
  "presets": ["@babel/preset-env"]
}

答案更新,感谢@ghanbari评论应用babel 7。

//✅使用模块。出口而不是出口 模块。出口= { 人, };