我试图在我的项目中运行一些ES6代码,但我得到了一个意外的令牌导出错误。
export class MyClass {
constructor() {
console.log("es6");
}
}
我试图在我的项目中运行一些ES6代码,但我得到了一个意外的令牌导出错误。
export class MyClass {
constructor() {
console.log("es6");
}
}
当前回答
通常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。
我的意见
出口
ES6
myClass.js
export class MyClass1 {
}
export class MyClass2 {
}
other.js
import { MyClass1, MyClass2 } from './myClass';
CommonJS替代
myClass.js
class MyClass1 {
}
class MyClass2 {
}
module.exports = { MyClass1, MyClass2 }
// or
// exports = { MyClass1, MyClass2 };
other.js
const { MyClass1, MyClass2 } = require('./myClass');
出口违约
ES6
myClass.js
export default class MyClass {
}
other.js
import MyClass from './myClass';
CommonJS替代
myClass.js
module.exports = class MyClass1 {
}
other.js
const MyClass = require('./myClass');
只需使用tsx作为运行时而不是节点。它将允许你使用正常的import语句,而不必将你的项目切换到type: module,也不必处理type: module的讨厌后果。此外,你还将获得TypeScript支持。
可能的答案
我有这个问题,在我的情况下发生的是,我缺乏添加扩展到文件 < <文件。ts > >
当我试图在我的项目中导入本地javascript模块时,我也得到了意外的令牌导出错误。当在index.html文件中添加脚本标记时,我通过将类型声明为模块来解决这个问题。
<script SRC = "。/path/to/the/module/" type = "module"></script> .