How to use ECMAScript6 modules within webpages

后端 未结 4 947
臣服心动
臣服心动 2020-12-08 07:11

I\'m pretty excited about using ECMAScript 6 features now via Babeljs - in particular, I\'d love to start making my JavaScript code more modular using the new modules featur

4条回答
  •  难免孤独
    2020-12-08 07:49

    I started out by trying the same thing, but eventually found that Gulp really helped out a lot.

    One thing to keep in mind: babel source.js > destination.js won't polyfill new ES6 syntax. Your code right now isn't using any let statements, destructured assignment, generator functions, or anything like that; but if you do add that at a later stage, you will need a more sophisticated transformation.

    Here is an answer that explains how to setup the gulp file: Javascript 6to5 (now Babel) export module usage (Disclaimer: It is one of my answers :P)

    Here are the steps specific to your case:

    1. Create a file called gulpfile.js in your directory with the following in it:
    var gulp = require('gulp');
    var browserify = require('browserify');
    var babelify= require('babelify');
    var util = require('gulp-util');
    var buffer = require('vinyl-buffer');
    var source = require('vinyl-source-stream');
    var uglify = require('gulp-uglify');
    var sourcemaps = require('gulp-sourcemaps');
    
    gulp.task('build', function() {
      browserify(['./lib.js', './main.js'], { debug: true })
      .add(require.resolve('babel/polyfill'))
      .transform(babelify)
      .bundle()
      .on('error', util.log.bind(util, 'Browserify Error'))
      .pipe(source('app.js'))
      .pipe(buffer())
      .pipe(sourcemaps.init({loadMaps: true}))
      .pipe(uglify({ mangle: false }))
      .pipe(sourcemaps.write('./'))
      .pipe(gulp.dest('./'));
    });
    
    gulp.task('default', ['build']);
    
    1. Run npm install gulp browserify babel babelify gulp-util vinyl-buffer vinyl-source-stream gulp-uglify gulp-sourcemaps to install the needed dependencies.
    2. Run gulp to bundle everything together.
    3. Use the bundled script in your HTML with this element:

    The nice thing in addition to polyfills being added is that the code is minified, and you get sourcemaps, which means even in your developer tools, you can debug the ES6 code itself.


    Note: While the import statement you are using is correct according to the ES6 draft specification, Babel won't like it. You will need to add a ./, so that it looks something like this:

    import { square, diag } from './lib';
    

    I suspect this is because the transformation happens in Node.js, and this differentiates a file from a node module. As a side point, you can write ES6 for node do requires with import statements :)

提交回复
热议问题