使用 babel 时是否需要 require js? [英] Do I need require js when I use babel?

查看:21
本文介绍了使用 babel 时是否需要 require js?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在试验 ES6,我使用 gulp 构建并使用 babel 转译到 ES5.输出不在节点中运行,只是从带有标记的 .htm 文件链接到.我想我需要添加

Im experimenting with ES6, and Im using gulp to build and babel to transpile to ES5. The output is not being run in node, just linked to from a .htm file with a tag. Im thinking I need to add

<script src='require.js'></script>

或类似的东西.

我正在尝试导入/导出.

Im trying to import / export.

////////////////scripts.js
import {Circle} from 'shapes';

c = new Circle(4);

console.log(c.area());


/////////////////shapes.js
export class Circle {

    circle(radius) {
        this.radius = radius;
    }

    area() {
        return this.radius * this.radius * Math.PI;
    } 

}

错误是

Uncaught ReferenceError: require is not defined

指的是这个(gulp中的.pipe(babel())之后)

Refers to this (after .pipe(babel()) in gulp)

var _shapes = require('shapes');

推荐答案

使用 babel 时是否需要 require js?

您可能需要一些模块加载器,但不是必需的 RequireJS.您有多种选择.以下内容将帮助您入门.

You might need some module loader, but it is not necessary RequireJS. You have several options. The following will help you to get started.

Rollup 是下一代 JavaScript 模块打包器.它本机理解 ES2015 模块,并将生成一个不需要任何模块加载器来操作的包.未使用的导出将从输出中修剪,这称为摇树.

Rollup is a next-generation JavaScript module bundler. It understands ES2015 modules natively, and will produce a bundle that doesn't need any module loader to operate. Unused exports will be trimmed from the output, it's called tree-shaking.

现在我个人推荐使用 rollupjs,因为它产生最清晰的输出,并且易于设置,但是,它为答案提供了不同的方面.所有其他方法都执行以下操作:

Now I personally recommend using rollupjs, as it produces the clearest output, and is easy to setup, however, it gives a different aspect to the answer. All the other approaches do the following:

  1. 使用 babel 编译 ES6 代码,使用您选择的模块格式
  2. 将编译后的模块与模块加载器连接在一起,或者使用一个打包器来为您遍历依赖项.

使用 rollupjs 时,事情就不是这样了.在这里, rollup 是第一步,而不是 babel.它默认只理解 ES6 模块.您必须提供一个入口模块,其中的依赖项将被遍历和连接.由于 ES6 允许在一个模块中存在多个命名导出,因此 rollupjs 足够智能,可以去除未使用的导出,从而缩小包的大小.不幸的是 rollupjs-s 解析器不理解 >ES6 语法,所以 ES7 模块必须在 rollup 解析它们之前编译,但编译不应该影响 ES6 导入.它是通过使用 rollup-plugin-babel 插件和 babel-preset-es2015-rollup 预设来完成的(这个预设与 es2015 相同,除了模块变压器和外部助手插件).因此,如果正确设置,rollup 将对您的模块执行以下操作:

With rollupjs things doesn't really work this way. Here, rollup is the first step, instead of babel. It only understands ES6 modules by default. You must give an entry module of which the dependencies will be traversed and concatenated. As ES6 allows multiple named exports in a module, rollupjs is smart enough to strip unused exports, thus shrinking bundle size. Unfortunately rollupjs-s parser doesn't understand >ES6 syntax, so ES7 modules have to be compiled before rollup parses them, but the compilation should not affect the ES6 imports. It is done by using the rollup-plugin-babel plugin with the babel-preset-es2015-rollup preset (this preset is the same as the es2015 one, except the module transformer and the external-helpers plugin). So rollup will do the following with your modules if correctly set up:

  1. 从文件系统中读取 ES6-7 模块
  2. babel 插件在内存中将其编译为 ES6
  3. rollup 解析 ES6 代码进行导入导出(使用 acorn 解析器,编译成 rollup)
  4. 它遍历整个图,并创建一个包(它仍然可能具有外部依赖关系,并且可能会以您选择的格式导出条目的导出)

示例 nodejs 构建:

// setup by `npm i rollup rollup-plugin-babel babel-preset-es2015 babel-plugin-external-helpers --save-dev`

// build.js:
require("rollup").rollup({
  entry: "./src/main.js",
  plugins: [
    require("rollup-plugin-babel")({
      "presets": [["es2015", { "modules": false }]],
      "plugins": ["external-helpers"]
    })
  ]
}).then(bundle => {
  var result = bundle.generate({
    // output format - 'amd', 'cjs', 'es6', 'iife', 'umd'
    format: 'iife'
  });

  require("fs").writeFileSync("./dist/bundle.js", result.code);
  // sourceMaps are supported too!
}).then(null, err => console.error(err));

使用 grunt-rollup

构建示例 grunt

Example grunt build with grunt-rollup

// setup by `npm i grunt grunt-rollup rollup-plugin-babel babel-preset-es2015 babel-plugin-external-helpers --save-dev`

// gruntfile.js
module.exports = function(grunt) {
  grunt.loadNpmTasks("grunt-rollup");
  grunt.initConfig({
    "rollup": {
      "options": {
        "format": "iife",
        "plugins": [
          require("rollup-plugin-babel")({
            "presets": [["es2015", { "modules": false }]],
            "plugins": ["external-helpers"]
          })
        ]
      },
      "dist": {
        "files": {
          "./dist/bundle.js": ["./src/main.js"]
        }
      }
    }
  });
}

gulp 构建示例,使用 gulp-rollup

// setup by `npm i gulp gulp-rollup rollup-plugin-babel babel-preset-es2015 babel-plugin-external-helpers --save-dev`

// gulpfile.js
var gulp       = require('gulp'),
    rollup     = require('gulp-rollup');

gulp.task('bundle', function() {
  gulp.src('./src/**/*.js')
    // transform the files here.
    .pipe(rollup({
      // any option supported by Rollup can be set here.
      "format": "iife",
      "plugins": [
        require("rollup-plugin-babel")({
          "presets": [["es2015", { "modules": false }]],
          "plugins": ["external-helpers"]
        })
      ],
      entry: './src/main.js'
    }))
    .pipe(gulp.dest('./dist'));
});


Babelify + 浏览

Babel 有一个简洁的包,名为 babelify.它的用法简单明了:


Babelify + Browserify

Babel has a neat package called babelify. It's usage is simple and straightforward:

$ npm install --save-dev babelify babel-preset-es2015 babel-preset-react
$ npm install -g browserify
$ browserify src/script.js -o bundle.js 
  -t [ babelify --presets [ es2015 react ] ]

或者你可以在 node.js 中使用它:

or you can use it from node.js:

$ npm install --save-dev browserify babelify babel-preset-es2015 babel-preset-react

...

var fs = require("fs");
var browserify = require("browserify");
browserify(["./src/script.js"])
  .transform("babelify", {presets: ["es2015", "react"]})
  .bundle()
  .pipe(fs.createWriteStream("bundle.js"));

这将立即转译和连接您的代码.Browserify 的 .bundle 将包含一个漂亮的小 CommonJS 加载器,并将您的转换模块组织成函数.你甚至可以有相对导入.

This will transpile and concatenate your code at once. Browserify's .bundle will include a nice little CommonJS loader, and will organize your transpiled modules into functions. You can even have relative imports.

// project structure
.
+-- src/
|   +-- library/
|   |   -- ModuleA.js
|   +-- config.js
|   -- script.js
+-- dist/
-- build.js
...

// build.js
var fs = require("fs");
var browserify = require("browserify");
browserify(["./src/script.js"])
  .transform("babelify", {presets: ["es2015", "react"]})
  .bundle()
  .pipe(fs.createWriteStream("dist/bundle.js"));

// config.js
export default "Some config";

// ModuleA.js
import config from '../config';
export default "Some nice export: " + config;

// script.js
import ModuleA from './library/ModuleA';
console.log(ModuleA);

要编译,只需在项目根目录中运行 node build.js.

To compile just run node build.js in your project root.

使用 babel 编译所有代码.我建议您使用 amd 模块转换器(在 babel 6 中称为 babel-plugin-transform-es2015-modules-amd).之后,将您编译的源代码与 WebPack 捆绑在一起.

Compile all your code using babel. I recommend you to use the amd module transformer (called babel-plugin-transform-es2015-modules-amd in babel 6). After that bundle your compiled sources with WebPack.

WebPack 2 出来了!它理解原生 ES6 模块,并且将使用 babili-s 内置来执行(或者说模拟)摇树死代码消除.目前(2016 年 9 月)我仍然建议将 rollup 与 babel 一起使用,尽管我的观点可能会随着 WebPack 2 的第一个版本而改变.请随时在评论中讨论您的意见.

WebPack 2 is out! It understands native ES6 modules, and will perform (or rather simulate) tree shaking using babili-s builtin dead code elimination. For now (September 2016) I would still suggest to use rollup with babel, although my opinion might change with the first release of WebPack 2. Feel free to discuss your opinions in the comments.

有时您希望对编译过程有更多的控制.您可以像这样实现自己的管道:

Sometimes you want to have more control over the compilation process. You can implement your own pipeline like this:

首先,您必须配置 babel 以使用 amd 模块.默认情况下,babel 转译为 CommonJS 模块,这在浏览器中处理有点复杂,尽管 browserify 设法以一种很好的方式处理它们.

First, you have to configure babel to use amd modules. By default babel transpiles to CommonJS modules, which is a little complicated to handle in the browser, although browserify manages to handle them in a nice way.

  • Babel 5:使用 { modules: 'amdStrict', ... } 选项
  • Babel 6:使用 es2015-modules-amd 插件
  • Babel 5: use { modules: 'amdStrict', ... } option
  • Babel 6: use the es2015-modules-amd plugin

不要忘记打开 moduleIds: true 选项.

Don't forget to turn on the moduleIds: true option.

检查生成的模块名称的转换代码,定义的模块和所需的模块之间经常不匹配.请参阅 sourceRoot 和 moduleRoot.

Check the transpiled code for generated modul names, there are often mismatches between defined and required modules. See sourceRoot and moduleRoot.

最后,你必须有某种模块加载器,但这不是必需的 requirejs.有 almondjs,这是一个运行良好的小需求垫片.您甚至可以实现自己的:

Finally, you have to have some kind of module loader, but it isn't necessairy requirejs. There is almondjs, a tiny require shim that works well. You can even implement your own:

var __modules = new Map();

function define(name, deps, factory) {
    __modules.set(name, { n: name, d: deps, e: null, f: factory });
}

function require(name) {
    const module = __modules.get(name);
    if (!module.e) {
        module.e = {};
        module.f.apply(null, module.d.map(req));
    }
    return module.e;

    function req(name) {
        return name === 'exports' ? module.e : require(name);
    }
}

最后,您可以将加载器 shim 和已编译的模块连接在一起,并在其上运行 uglify.

At the end, you can just concatenate the loader shim and the compiled modules together, and running an uglify on that.

默认情况下,上面的大多数方法都是用 babel 单独编译每个模块,然后将它们连接在一起.这也是 babelify 所做的.但是如果你查看编译后的代码,你会发现 babel 在每个文件的开头插入了很多样板,其中大部分在所有文件中都是重复的.

By default, most of the above methods compile each module with babel individually, and then concatenate them together. That's what babelify does too. But if you look at the compiled code, you see that babel inserts lots of boilerplate at the beginning of each file, most of them are duplicated across all files.

为了防止这种情况,您可以使用 babel-plugin-transform-runtime 插件.

To prevent this you can use the babel-plugin-transform-runtime plugin.

这篇关于使用 babel 时是否需要 require js?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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