我是ES6的新手,请原谅我,如果这是一个重复的问题。正如标题所述,我目前正在收到错误:
未捕获的SyntaxError:意外的令牌导入
显然,对象Person尚未成功导入以在app.js
文件中使用。
我查看了网络上的示例代码,但仍无法正常工作。我怀疑它与webpack.config.js
设置有关。
我也尝试使用let person = require("./modules/Person");
,但它不起作用。
请有任何想法?他们将非常感激。
我在下面提供了代码摘录:
的src / JS /模块/ person.js
class Person {
constructor(name, jobtitle, sex){
this.name = name;
this.jobtitle = jobtitle;
this.message = document.getElementById("message").html;
this.sex = sex;
}
Greet(){
console.log("Hello, my name is "+ this.name + " and i am a " + sex);
}
EchoOccupation(){
console.log("I am a "+ this.jobtitle);
}
EchoMessage(){
console.log("The message is "+ this.message);
}
}
module.exports = Person;
的src / JS / app.js
import { Person } from './modules/person';
let vic = new Person("Fred", "Web Developer", "male");
vic.Greet();
vic.EchoOccupation("Web Developer");
webpack.config.js
var path = require("path"),
watchBabel = require("watch-babel"),
srcJsDir = "./src/js/",
srcDestJsDir = "dist/assets/js/",
options = { glob: "src/*.js" },
watcher = watchBabel(srcJsDir, srcDestJsDir, options);
watcher.on("ready", function() {
console.log("ready");
}).on("success", function(filepath) {
console.log("Transpiled ", filepath);
}).on("failure", function(filepath, e) {
console.log("Failed to transpile", filepath, "(Error: ", e);
}).on("delete", function(filepath) {
console.log("Deleted file", filepath);
});
module.exports = {
entry: [srcJsDir + "/app.js"],
output: {
path: srcDestJsDir,
filename: "app.js"
},
watch: true,
devServer: {
inline: true,
port: 8000
},
module: {
loader : [
{
test: /\.js$/,
exclude: "/node_modules/",
loaders: ['babel', 'watch-babel'],
query: {
presets: ['es2015'],
plugins: ['babel-plugin-uglify']
}
},
]
},
resolveLoader: {
root: path.join(__dirname, 'node_modules/')
}
};
的index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>im loving es6</title>
<link href="/src/css/frameworks/bootstrap.min.css" />
</head>
<body>
<header></header>
<main>
<div class="container">
<div class="row">
<div class="col-xs-12">
<article>
<section>
<div id="app"></div>
<div id="message">Hello this is my message!</div>
</section>
<aside></aside>
</article>
</div>
</div>
</div>
</main>
<footer></footer>
<script type="text/javascript" src="/dist/assets/js/app.js"></script>
</body>
</html>
答案 0 :(得分:4)
发生错误是因为从person.js
导出的模块没有Person
属性。
您可以通过进行三项更改来解决此问题:
<强>的src / JS /模块/ person.js 强>
class Person {
...
}
// Set the Person class as the object exported from this module
export default Person;
<强>的src / JS / app.js 强>
// Import the Person class
import Person from './modules/person';
<强> webpack.config.js 强>
...
module: {
// Rename the 'loader' property to 'loaders'
loaders: [
...
]
}
您可以在此处找到有关import
的更多信息:ES6 import