我试图在我的项目中运行一些ES6代码,但我得到了一个意外的令牌导出错误。
export class MyClass {
constructor() {
console.log("es6");
}
}
我试图在我的项目中运行一些ES6代码,但我得到了一个意外的令牌导出错误。
export class MyClass {
constructor() {
console.log("es6");
}
}
当前回答
//✅使用模块。出口而不是出口 模块。出口= { 人, };
其他回答
可能的答案
我有这个问题,在我的情况下发生的是,我缺乏添加扩展到文件 < <文件。ts > >
通常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>
最后在活动服务器上运行此代码
此时没有必要使用Babel (JS已经变得非常强大),因为您可以简单地使用默认的JavaScript模块导出。查看完整教程
Message.js
module.exports = 'Hello world';
app.js
var msg = require('./Messages.js');
console.log(msg); // Hello World
实际上我想添加一个简单的解决方案。使用常量反撇号(')。
const model = `<script type="module" src="/"></<script>`
我通过制作一个入口点文件来解决这个问题。
// index.js
require = require('esm')(module)
module.exports = require('./app.js')
我在app.js内外导入的任何文件都可以使用导入/导出 现在你可以像node index.js一样运行它
注意:如果app.js使用export default,在使用入口点文件时,这将变成require('./app.js').default。