import export 和babel

使用babelimport轉換成node能使用的語法:

  1. 安裝:npm install babel-cli babel-preset-env -D;
  2. 添加.babelrc文件:
    {
      "presets": [
        [
          "env",
          {
            "targets": {
              "node": "current"
            }
          }
        ]
      ]
    }
    

    3.

  3. 安裝nodemon :npm install nodemon -D;

  4. 修改package.json:

    "scripts": {
        "dev": "nodemon -w src --exec \"babel-node src --prosets env\""
      },

    監控src文件夾下內容的變化

  5. 、src/expo.js

    export const name = 'luke'
    export const getName = function (params) {
      return 'luke'
    }
    const age = 31
    export default age
    
    export { // 批量導出
      name as name2,
      getName as getName2,
      age as age2
    }

    在src/index.js做導入使用:

    import { name } from "./expo";
    import { getName } from "./expo";
    import { name, getName } from "./expo";
    import age from "./expo";
    import { name as name3, 
             getName2 as getName3,
             age as age2 } from "./expo";
    console.log(name);
    console.log(getName());

     

  6. export default 導出的,在導入的時候,不需要{};

  7. 生產環境使用babel,支持es6-7:在package.json下添加命令:

    "scripts": {
        "build": "babel src -s -D -d dist --presets env"
      },

    這樣就把該目錄下的文件都編譯到了dist目錄下

  8. 用rimraf模塊可以做新增的編譯監控,先刪除舊的文件,再編譯新的文件:npm install -D rimraf ;之後配置package.json文件中的

    "scripts": {
        "dev": "nodemon -w src --exec \"babel-node src --prosets env\"",
        "build": "rimraf dist && babel src -s -D -d dist --presets env"
      },

    之後修改index.js,

  9. 在package.json裏面添加:

     "scripts": {
        "production": "node dist"
      },

    這時候使用命令npm run production 則會報錯:regeneratorRuntime is not defined;

  10. 上面的原因是因爲Async 轉generator Function的時候,Async是ES7(ex2016)的特性,所以要借住插件:npm install -S babel-plugin-transform-runtime babel-runtime,安裝之後,需要配置一下.babelrc文件:

    {
      "presets": [
        [
          "env",
          {
            "targets": {
              "node": "current"
            }
          }
        ]
      ],
      "plugins": [
        [
          "transform-runtime", {
            "polyfill": false,
            "regenerator": true
          }
        ]
      ]
      // "plugins": ["transform-runtime"],
      // "comments": false
    }
    

    在重新npm run build --npm run production 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章