简体   繁体   English

如何使用Babel和Grunt正确编译项目

[英]How to compile a project properly with Babel and Grunt

I'm trying to play with Babel, but it doesn't work well for me. 我正在尝试使用Babel,但它对我来说效果不佳。

My project is simple 我的项目很简单

|-project/
|---src/
|-----index.html
|-----main.js
|-----module.js
|---Gruntfile.js
|---package.json

index.html 的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 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 module.js

export function sum(x, y) {
    return x + y;
}

Gruntfile.js 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"]);
};

I run grunt, everything compile. 我运行咕噜声,一切都编译。 But I can't use have the expected result. 但我不能使用有预期的结果。

First, the browser say require is not defined , so I add require.js to my HTML. 首先,浏览器说require is not defined ,所以我将require.js添加到我的HTML中。

Then, I get Error: Module name "module" has not been loaded yet for context: _. Use require([]) http://requirejs.org/docs/errors.html#notloaded 然后,我得到Error: Module name "module" has not been loaded yet for context: _. Use require([]) http://requirejs.org/docs/errors.html#notloaded Error: Module name "module" has not been loaded yet for context: _. Use require([]) http://requirejs.org/docs/errors.html#notloaded

I'm a bit confused about all of these. 我对所有这些都有些困惑。 How I can make my code work? 我如何使我的代码工作?

To expand on veg_prog's answer, you should use something like Browserify if you want to organize your code into modules. 要扩展veg_prog的答案,如果要将代码组织到模块中,则应使用类似Browserify的内容。 Browserify can be used with Grunt via grunt-browserify , and Babel can be used with Browserify via babelify . Browserify可以通过grunt- browserify与Grunt一起使用,Babel可以通过babelify与Browserify一起使用。

I've tweaked some of your files to show you how it can be done: 我已经调整了一些文件来向您展示如何完成它:

index.html 的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 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 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 的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"
  }
}

Babel uses 'common' by default. Babel默认使用'common'。 That doesn't work for requirejs. 这对requirejs不起作用。 So, change modules to 'amd'. 所以,将模块更改为'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"
        }]
    }
}

Update for Babel6. Babel6的更新。 See also http://babeljs.io/docs/plugins/transform-es2015-modules-amd/ and https://babeljs.io/docs/plugins/ 另见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"
        }]
    }
}

First, the browser say require is not defined, so I add require.js to my HTML. 首先,浏览器说require没有定义,所以我将require.js添加到我的HTML中。

I don't think, that adding require.js will be the solution. 我不认为,添加require.js将是解决方案。 In this context require is node-style syntax: ( https://github.com/substack/browserify-handbook#user-content-require ). 在此上下文中,require是节点式语法:( https://github.com/substack/browserify-handbook#user-content-require )。

Browserify is a module loader but works different than requirejs. Browserify是一个模块加载器,但与requirejs不同。 There is a babel distribution for requirejs, too ( https://github.com/mikach/requirejs-babel ) but I recommend using browserify. requirejs也有一个babel发行版( https://github.com/mikach/requirejs-babel ),但我建议使用browserify。

In a setup, where babel is working with browserify, something like this 在一个设置中,babel正在使用browserify,就像这样

import $ from'jquery';

will become something like this 将成为这样的事情

var $ = require('jquery');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM