如何用Babel和Grunt正确编译项目 [英] How to compile a project properly with Babel and Grunt

查看:82
本文介绍了如何用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>测试< /标题>
< script src =main.jstype =application / javascript>< / script>
< / head>
< body>
< p>简单的html文件。< / p>
< / body>
< / html>

main.js

  import *作为./module的数学运算; 

异步函数anwser(){
return 42;

$ b(function main(){
anwser()。then((v)=> {
console.info(v);
)};

console.log(math.sum(5,5));
})();

module.js

 导出函数sum(x,y){
return x + y;
}

Gruntfile.js

  module.exports = function(grunt){

grunt.initConfig({
babel:{
options:{
sourceMap:true,
experimental:true
},
dist:{
files:[{
展开: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没有定义,所以我添加require.js到我的HTML。

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



我有点困惑所有这些。如何使我的代码工作?

解决方案

为了扩展veg_prog的答案,如果想组织你的代码进入模块。 Browserify可以通过 grunt-browserify 与Grunt一起使用,而Babel可以通过 babelify



我调整了一些文件向您展示如何完成它:



index.html

 <!DOCTYPE html> 
< html>
< head lang =en>
< meta charset =UTF-8>
< title>测试< /标题>
< script src =bundle.jstype =application / javascript>< / script>
< / head>
< body>
< p>简单的html文件。< / p>
< / body>
< / html>

main.js

 导入babelify / polyfill; //需要巴贝尔的实验功能。 
导入*作为./module的数学运算;

异步函数anwser(){
return 42;

$ b(function main(){
anwser()。then((v)=> {
console.info(v);
)};

console.log(math.sum(5,5));
})();

Gruntfile.js

  module.exports = function(grunt){

grunt.initConfig({
browserify:{
dist:{
选项:{
转换:[[babelify,{stage:0}]]
},
文件:{
build / bundle.js :src / main.js
}
}
},
htmlmin:{
dist:{
options:{
removeComments:true,
collapseWhitespace:true
},
files:[{
expand:true,
cwd:src /,
src:[** / *。html],
dest:build /,
ext:.html
}]
$ b $ {
scripts:{
files:src / *。js,
tasks:[browserify]
},
html:{
文件: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

}


I'm trying to play with Babel, but it doesn't work well for me.

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

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

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.

Then, I get 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. Browserify can be used with Grunt via grunt-browserify, and Babel can be used with Browserify via babelify.

I've tweaked some of your files to show you how it can be done:

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'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"
  }
}

这篇关于如何用Babel和Grunt正确编译项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆