Как правильно скомпилировать проект с Babel и Grunt
Я пытаюсь играть с Вавилоном, но для меня это не сработает.
Мой проект прост
|-project/
|---src/
|-----index.html
|-----main.js
|-----module.js
|---Gruntfile.js
|---package.json
index.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));
})();
module.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"]);
};
Я запускаю хрюкать, все компилируется. Но я не могу использовать ожидаемый результат.
Во-первых, браузер говорит 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
Я немного смущен обо всех этих. Как я могу заставить мой код работать?
Ответы
Ответ 1
Чтобы расширить ответ на veg_prog, вы должны использовать что-то вроде Browserify, если хотите организовать свой код в модули. Browserify можно использовать с Grunt через grunt-browserify, а Babel можно использовать с Browserify через babelify.
Я изменил некоторые из ваших файлов, чтобы показать вам, как это можно сделать:
index.html
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Test</title>
<script src="bundle.js" type="application/javascript"></script>
</head>
<body>
<p>Simple html file.</p>
</body>
</html>
main.js
import "babelify/polyfill"; // Needed for Babel experimental features.
import * as math from "./module";
async function anwser() {
return 42;
}
(function main() {
anwser().then((v) => {
console.info(v);
});
console.log(math.sum(5, 5));
})();
Gruntfile.js
module.exports = function(grunt) {
grunt.initConfig({
browserify: {
dist: {
options: {
transform: [["babelify", { "stage": 0 }]]
},
files: {
"build/bundle.js": "src/main.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: ["browserify"]
},
html: {
files: "src/*.html",
tasks: ["htmlmin"]
}
}
});
grunt.loadNpmTasks("grunt-browserify");
grunt.loadNpmTasks("grunt-contrib-watch");
grunt.loadNpmTasks("grunt-contrib-htmlmin");
grunt.registerTask("default", ["browserify", "htmlmin"]);
};
package.json
{
"devDependencies": {
"babelify": "6.0.1",
"grunt": "0.4.5",
"grunt-browserify": "3.6.0",
"grunt-contrib-htmlmin": "0.4.0",
"grunt-contrib-watch": "0.6.1"
}
}
Ответ 2
Бабель использует "общий" по умолчанию. Это не работает для requirejs.
Итак, измените модули на 'amd'.
"babel": {
"options": {
"sourceMap": true,
"experimental": true,
"modules": "amd" //This is the line to be added.
},
dist: {
files: [{
"expand": true,
"cwd": "src/",
"src": ["**/*.js"],
"dest": "build/",
"ext": ".js"
}]
}
}
Обновление для Babel6. См. Также http://babeljs.io/docs/plugins/transform-es2015-modules-amd/
и https://babeljs.io/docs/plugins/
"babel": {
"options": {
"sourceMap": true,
"experimental": true,
"plugins": ["transform-es2015-modules-amd"] //This is the line to be added.
},
dist: {
files: [{
"expand": true,
"cwd": "src/",
"src": ["**/*.js"],
"dest": "build/",
"ext": ".js"
}]
}
}
Ответ 3
Во-первых, браузер говорит, что требование не определено, поэтому я добавляю require.js в свой HTML.
Я не думаю, что добавление require.js будет решением.
В этом контексте требуется синтаксис node -style:
(https://github.com/substack/browserify-handbook#user-content-require).
Browserify - это загрузчик модулей, но работает по-другому, чем requirejs.
Существует также распределение babel для requirejs (https://github.com/mikach/requirejs-babel), но я рекомендую использовать браузеру.
В настройке, где babel работает с браузером, что-то вроде этого
import $ from'jquery';
станет чем-то вроде этого
var $ = require('jquery');