我爱编程

babel 将es6编译成es6和es5

2017-09-20  本文已影响186人  别过经年

项目中遇到了个问题,就是我们的utils项目是独立的项目然后发布到公司内部的npm仓库,我们的代码都是用typescript写的,然后在其他项目yarn add xxx 这样就被添加到了node_modules目录下面

 "build": "rm -rf lib && rm -rf es6 && rm -rf typings && tsc -p ./ --outDir es6/ -d --declarationDir typings/ && babel es6 --out-dir lib",

这么的话生成三个目录typings es6 lib 三个目录,但是debug的时候发现Chrome Sources面板下面只有编译成es5的lib目录,该项目使用了redux-saga就有了yield关键字,编译成es5后就是一堆switch case看起来很不方便,要是能在Chrome sources面板直接调试typescript或者es6代码就方便多了,查了下有人说是在tsconfig.json或者webpack配置下 "sourceMap": true,我下载该项目加上source map,然后拷贝到node_modules下面,但没有执行,报错

webpack2 终极优化这篇文章提到了redux编译的时候有require和import模式

package.json

    "build:commonjs": "cross-env BABEL_ENV=commonjs babel src --out-dir lib",
    "build:es": "cross-env BABEL_ENV=es babel src --out-dir es",

.bablerc

{
  "plugins": [
    ["transform-es2015-template-literals", { "loose": true }],
    "transform-es2015-literals",
    "transform-es2015-function-name",
    "transform-es2015-arrow-functions",
    "transform-es2015-block-scoped-functions",
    ["transform-es2015-classes", { "loose": true }],
    "transform-es2015-object-super",
    "transform-es2015-shorthand-properties",
    ["transform-es2015-computed-properties", { "loose": true }],
    ["transform-es2015-for-of", { "loose": true }],
    "transform-es2015-sticky-regex",
    "transform-es2015-unicode-regex",
    "check-es2015-constants",
    ["transform-es2015-spread", { "loose": true }],
    "transform-es2015-parameters",
    ["transform-es2015-destructuring", { "loose": true }],
    "transform-es2015-block-scoping",
    "transform-object-rest-spread",
    "transform-es3-member-expression-literals",
    "transform-es3-property-literals"
  ],
  "env": {
    "commonjs": {
      "plugins": [
        ["transform-es2015-modules-commonjs", { "loose": true }]
      ]
    },
    "es": {
      "plugins": [
        "./build/use-lodash-es"
      ]
    }
  }
}

use-lodash-es.js

module.exports = function () {//这边的代码不理解,这么写就可以是import的方式引入模块了吗
  return {
    visitor: {
      ImportDeclaration(path) {
        const source = path.node.source
        source.value = source.value.replace(/^lodash($|\/)/, 'lodash-es$1')
      }
    }
  }
}

webpack2 终极优化

上一篇下一篇

猜你喜欢

热点阅读