我正在尝试和 Babel 一起玩,但它对我来说效果不佳。
我的项目很简单
|-project/
|---src/
|-----index.html
|-----main.js
|-----module.js
|---Gruntfile.js
|---package.json
索引.html
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Test</title>
<script src="main.js" type="application/javascript"></script>
</head>
<body>
<p>Simple html file.</p>
</body>
</html>
main.js
import * as math from "./module";
async function anwser() {
return 42;
}
(function main() {
anwser().then((v) => {
console.info(v);
});
console.log(math.sum(5, 5));
})();
模块.js
export function sum(x, y) {
return x + y;
}
Gruntfile.js
module.exports = function(grunt) {
grunt.initConfig({
"babel": {
"options": {
"sourceMap": true,
"experimental": true
},
dist: {
files: [{
"expand": true,
"cwd": "src/",
"src": ["**/*.js"],
"dest": "build/",
"ext": ".js"
}]
}
},
htmlmin: {
dist: {
options: {
removeComments: true,
collapseWhitespace: true
},
files: [{
"expand": true,
"cwd": "src/",
"src": ["**/*.html"],
"dest": "build/",
"ext": ".html"
}]
}
},
watch: {
scripts: {
files: 'src/*.js',
tasks: ["babel"]
},
html: {
files: 'src/*.html',
tasks: ["htmlmin"]
}
}
});
grunt.loadNpmTasks('grunt-babel');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-htmlmin');
grunt.registerTask("default", ["babel", "htmlmin"]);
};
我运行 grunt,一切编译。但我不能使用有预期的结果。
首先,浏览器说require is not defined
,所以我将 require.js 添加到我的 HTML 中。
然后,我得到Error: Module name "module" has not been loaded yet for context: _. Use require([]) http://requirejs.org/docs/errors.html#notloaded
我对所有这些都感到有些困惑。我怎样才能使我的代码工作?