programing

바벨을 사용할 때 js가 필요합니까?

nasanasas 2020. 9. 12. 10:07
반응형

바벨을 사용할 때 js가 필요합니까?


나는 ES6으로 실험하고 있고, 나는 gulp를 사용하여 빌드하고 바벨을 사용하여 ES5로 트랜스 파일합니다. 출력은 노드에서 실행되지 않고 태그가있는 .htm 파일에서 링크됩니다. 내가 추가해야 할 것 같아

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

또는 그런 것.

가져 오기 / 내보내기를 시도하고 있습니다.

////////////////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 ()) 이후)

var _shapes = require('shapes');

바벨을 사용할 때 js가 필요합니까?

모듈 로더가 필요할 수 있지만 RequireJS는 필요하지 않습니다. 몇 가지 옵션이 있습니다. 다음은 시작하는 데 도움이됩니다.


rollup.js롤업 - 플러그인 - 바벨

Rollup은 차세대 JavaScript 모듈 번 들러입니다. ES2015 모듈을 기본적으로 이해하고 작동하는 데 모듈 로더가 필요하지 않은 번들을 생성합니다. 사용하지 않은 내보내기는 출력에서 ​​트리밍되며이를 트리 쉐이킹이라고합니다.

이제는 가장 명확한 출력을 생성하고 설정하기 쉽기 때문에 개인적으로 rollupjs를 사용하는 것이 좋지만 대답에 다른 측면을 제공합니다. 다른 모든 접근 방식은 다음을 수행합니다.

  1. 바벨로 ES6 코드를 컴파일하고 원하는 모듈 형식을 사용합니다.
  2. 컴파일 된 모듈을 모듈 로더와 함께 연결하거나 종속성을 탐색하는 번 들러를 사용하십시오.

rollupjs를 사용하면 실제로 이런 식으로 작동하지 않습니다. 여기서 롤업은 바벨이 아닌 첫 번째 단계입니다. 기본적으로 ES6 모듈 만 이해합니다. 종속성이 순회되고 연결될 항목 모듈을 제공해야합니다. ES6는 모듈에서 여러 개의 명명 된 내보내기를 허용하므로 rollupjs는 사용하지 않는 내보내기를 제거 할 수있을만큼 똑똑하므로 번들 크기가 줄어 듭니다. 불행히도 rollupjs-s 파서는> ES6 구문을 이해하지 못하므로 ES7 모듈은 롤업에서 파싱하기 전에 컴파일해야하지만 컴파일은 ES6 가져 오기에 영향을주지 않아야합니다. 사전 설정이 있는 rollup-plugin-babel플러그인을 사용하여 수행됩니다 babel-preset-es2015-rollup(이 사전 설정은 모듈 변환기 및 외부 도우미 플러그인을 제외하고 es2015의 사전 설정과 동일합니다). 따라서 롤업은 올바르게 설정된 경우 모듈에서 다음을 수행합니다.

  1. 파일 시스템에서 ES6-7 모듈을 읽습니다.
  2. babel 플러그인은 메모리에서 ES6로 컴파일합니다.
  3. rollup은 가져 오기 및 내보내기를 위해 ES6 코드를 구문 분석합니다 (롤업으로 컴파일 된 도토리 구문 분석기 사용).
  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 빌드의 예

// 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-rollup을 사용한 gulp 빌드 예제

// 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 + Browserify

Babel에는 babelify 라는 깔끔한 패키지가 있습니다 . 사용법은 간단하고 간단합니다.

$ 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에서 사용할 수 있습니다.

$ 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"));

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.

Example:

// 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);

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


Babel + 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 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.


Custom compilation pipeline

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

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: use { modules: 'amdStrict', ... } option
  • Babel 6: use the es2015-modules-amd plugin

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

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

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

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


Babel's boilerplate code is duplicated in every module

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.

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


barebones webpack 2

1) If this is your root directory:

index.html

<html>
  ...
  <script src="./bundle.js"></script>
  ...
</html>

scripts.js

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

shapes.js

export class Circle {
  ...
}

2) have node installed node

3) run the following command in your terminal:

$ npm install -g webpack

5) in your root directory run the following:

$ webpack scripts.js bundle.js

You should now have a file called bundle.js in your root directory which will be the file your index.html will consume. This is a minimalistic bundling feature from webpack. You can learn more here


require does not exist in the browser, so this error is expected. You need to use something like require.js or Browserify.

참고URL : https://stackoverflow.com/questions/31593694/do-i-need-require-js-when-i-use-babel

반응형