Es6-babel-browserify use tutorial

  1. Define the package.json file
{" name ":" es6 - Babel - browserify ", "version" : "1.0.0"}Copy the code
  1. Install babel-CLI, babel-PRESET – ES2015 and Browserify
  • npm install babel-cli browserify -g
    • npm install babel-preset-es2015 –save-dev
  1. Define the.babelrc file

    {
     "presets": ["es2015"]
      }
    Copy the code
  2. coding

  • js/src/module1.js

    export function foo() {
      console.log('module1 foo()');
    }
    export let bar = function () {
      console.log('module1 bar()');
    }
    export const DATA_ARR = [1, 3, 5, 1]
    Copy the code
  • js/src/module2.js

    let data = 'module2 data'
    
    function fun1() {
      console.log('module2 fun1() ' + data);
    }
    
    function fun2() {
      console.log('module2 fun2() ' + data);
    }
    
    export {fun1, fun2}
    Copy the code
  • js/src/module3.js

    export default {
      name: 'Tom',
      setName: function (name) {
        this.name = name
      }
    }
    Copy the code
  • js/src/app.js

    import {foo, bar} from './module1'
    import {DATA_ARR} from './module1'
    import {fun1, fun2} from './module2'
    import person from './module3'
    
    import $ from 'jquery'
    
    $('body').css('background', 'red')
    
    foo()
    bar()
    console.log(DATA_ARR);
    fun1()
    fun2()
    
    person.setName('JACK')
    console.log(person.name);
    Copy the code
  1. compile
  • Compile ES6 to ES5 code (but with CommonJS syntax) using Babel: Babel js/ src-d js/lib
  • Compile js with Browserify: Browserify js/lib/app.js -o js/lib/bundle.js
  1. Page to introduce tests
<script type="text/javascript" src="js/lib/bundle.js"></script>
Copy the code
  1. 1). Download jQuery module:

    • npm install jquery@1 –save 2). Introduced and used in app.js
    import $ from 'jquery'
    $('body').css('background', 'red')
    Copy the code