Cómo compilar un proyecto correctamente con Babel y Grunt


Estoy tratando de jugar con Babel, pero no funciona bien para mí.

Mi proyecto es simple

|-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));
})();

Módulo.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"]);
};

Corro grunt, todo compila. Pero no puedo usar tener el resultado esperado.

Primero, el navegador dice require is not defined, así que agrego require.js a mi HTML.

Entonces, obtengo Error: Module name "module" has not been loaded yet for context: _. Use require([]) http://requirejs.org/docs/errors.html#notloaded

Estoy un poco confundido acerca de todo esto. Cómo puedo hacer mi código trabajo?

Author: Philip Kirkbride, 2015-02-22

3 answers

Para ampliar la respuesta de veg_prog, debes usar algo como Browserify si quieres organizar tu código en módulos. Browserify se puede usar con Grunt via grunt-browserify , y Babel se puede usar con Browserify via babelify .

He ajustado algunos de sus archivos para mostrarle cómo puede ser hecho:

Índice.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's 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"]);
};

Paquete.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"
  }
}
 28
Author: XåpplI'-I0llwlg'I -,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-03 04:50:41

Babel usa 'common' por defecto. Eso no funciona para requirejs. Por lo tanto, cambie los módulos a '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"
        }]
    }
}

Actualización para Babel6. Véase también http://babeljs.io/docs/plugins/transform-es2015-modules-amd / y 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"
        }]
    }
}
 13
Author: Niels Steenbeek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-07 10:02:42

Primero, el navegador dice requerir no está definido, así que agrego requerir.js a mi HTML.

No creo, que la adición requiere.js será la solución. En este contexto require is sintaxis de estilo nodo: ( https://github.com/substack/browserify-handbook#user-content-require).

Browserify es un cargador de módulos, pero funciona de manera diferente a requirejs. También hay una distribución de babel para requirejs ( https://github.com/mikach/requirejs-babel ) pero recomiendo usando browserify.

En una configuración, donde babel está trabajando con browserify, algo como esto

import $ from'jquery';

Se convertirá en algo como esto

var $ = require('jquery');
 8
Author: veg_prog,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-28 06:24:53