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

标签 javascript gruntjs babeljs

我正在尝试使用 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>

主程序

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 中。

然后,我得到 错误:尚未为上下文加载模块名称“module”:_。使用 require([]) http://requirejs.org/docs/errors.html#notloaded

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

最佳答案

为了扩展 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"
  }
}

关于javascript - 如何使用 Babel 和 Grunt 正确编译项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28661499/

相关文章:

javascript - IIFE 创建模式 - 但如何支持构造函数参数?

javascript - 如何在 Javascript 中读取 Python 列表 [在 Django 模板中]

gruntjs - grunt-wiredep 和 Jade 模板

javascript - Grunt uncss 忽略 javascript 生成的 css

TypeScript TSConfig CompilerOptions ES2017 目标和库

javascript - 如何正确导出Webpack库?

javascript - NODE.JS 访问 EJS 模板中的函数

javascript - 奇怪的问题 div block 在 jquery 之后不会备份

javascript - PhantomJS 崩溃 - 退出代码 126

javascript - 如何在vue loader组件中导入JS脚本?