【发布时间】:2017-01-24 00:44:32
【问题描述】:
我对 ES6 很陌生,如果这是一个重复的问题,请原谅我。正如标题所述,我目前收到错误消息:
Uncaught SyntaxError: Unexpected token import
显然,对象 Person 尚未成功导入以用于 app.js 文件。
我查看了网络上的示例代码,但仍然无法正常工作。我怀疑它与webpack.config.js 设置有关。
我也尝试过使用let person = require("./modules/Person");,但它不起作用。
请问有什么想法吗?他们将不胜感激。
我在下面提供了代码摘录:
src/js/modules/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>
【问题讨论】:
-
对于您的直接问题,您想要编写如下内容似乎相对清楚: var Person = require('./modules/person');而不是使用“导入”。这将是语法错误的原因。我无法帮助您进行 Webpack 配置。啊,是的,你看,网络浏览器通常不理解新的“导入”语法。
-
感谢工作!还是不明白……我原以为 Webpack 会像“让”一样“转换”或转换“导入”关键字。另外,我尝试了“let person = require("./modules/Person");”同样,可能那时我正面临另一个错误(发布后我现在可以看到一些错误),但由于沮丧而没有意识到。
-
Babel 确实可以像这样转换导入,但请注意网络浏览器,例如最近的 Chrome,确实了解其他 ES6 语法,例如“let”。在我看来,错误的脚本正在按原样运行。