【问题标题】:How to compile a project properly with Babel and Grunt如何使用 Babel 和 Grunt 正确编译项目
【发布时间】:2015-02-22 18:22:42
【问题描述】:

我正在尝试和 Babel 一起玩,但对我来说效果不佳。

我的项目很简单

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

我运行 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

我对所有这些都有些困惑。我怎样才能让我的代码工作?

【问题讨论】:

    标签: javascript gruntjs babeljs


    【解决方案1】:

    要扩展 veg_prog 的答案,如果您想将代码组织成模块,您应该使用 Browserify 之类的东西。 Browserify 可以通过grunt-browserify 与 Grunt 一起使用,Babel 可以通过 babelify 与 Browserify 一起使用。

    我已经调整了您的一些文件以向您展示如何做到这一点:

    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>
    

    ma​​in.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"]);
    };
    

    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】:

      Babel 默认使用 'common'。这不适用于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"
              }]
          }
      }
      

      【讨论】:

      • 或者更好:'umd'
      【解决方案3】:

      首先,浏览器说 require 没有定义,所以我将 require.js 添加到我的 HTML 中。

      我不认为,添加 require.js 将是解决方案。 在这种情况下 require 是节点样式的语法: (https://github.com/substack/browserify-handbook#user-content-require)。

      Browserify 是一个模块加载器,但工作方式与 requirejs 不同。 requirejs 也有一个 babel 发行版 (https://github.com/mikach/requirejs-babel),但我建议使用 browserify。

      在 babel 使用 browserify 的设置中,类似这样的设置

      import $ from'jquery';
      

      会变成这样的

      var $ = require('jquery');
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-07-02
        • 2020-11-18
        • 1970-01-01
        • 1970-01-01
        • 2019-12-03
        • 2017-01-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多