平巴贝尔输出

时间:2016-12-12 20:58:17

标签: javascript babeljs

我在src目录中有一个嵌套文件结构的项目。到现在为止,我正在使用babel --out-dir lib src。最近我想出了让用户直接使用单独文件的想法,所以基本上我想改变这种结构:

| src/
|   a.js
|   b.js
|   c/
|     d.js
|     e/
|       f.js

进入这个:

| lib/
|   a.js
|   b.js
|   d.js
|   f.js

我已经尝试babel --out-dir lib src/*babel --out-dir lib src/**babel --out-dir lib src/**/*.js,但没有一个按预期工作 - 有些复制文件多次(一次在顶层,一次)在子目录中)或仅在子目录中。

2 个答案:

答案 0 :(得分:1)

不幸的是,仅使用babel命令无法完成,因为babel没有任何--no-recursive选项。

但是,如果你不怕分号和自由使用find,你可以用一个单行代码来做:

babel -d lib $(find src -type d); find lib/* -maxdepth 0 -type d | xargs rm -r

在:

$ tree src
src
├── a.js
├── b.js
└── c
    ├── d.js
    └── e
        └── f.js

后:

$ tree lib
lib
├── a.js
├── b.js
├── d.js
└── f.js

答案 1 :(得分:1)

我刚刚遇到babel-cli这个问题,它一直覆盖我的源文件内容。解决了Node脚本:

const babel = require('babel-core');
const glob = require('glob');
const fs = require('fs');

    // glob passes an array of path/filenames into callback as files
    glob('./src/**/*.js', {}, (er, files) => {
        // for each filename
        files.forEach(file => {
            // transform that filename, your presets/plugins may vary
            babel.transformFile(file, {presets: ['es2015', 'es2017', 'stage-3'], babelrc: false}, (err, result) => {
                if (!err) {
                    console.log(`${file} transpiled`);
                    // if it worked, write it to the new dir (in my case it's root)
                    fs.writeFileSync(`./${result.options.basename}.js`, result.code);
                }
            });
        })
    });

依赖关系:

"devDependencies": {
    "babel-core": "^6.26.0",
    "babel-eslint": "7",
    "babel-jest": "^20.0.3",
    "babel-loader": "^6.2.4",
    "babel-plugin-istanbul": "^4.1.4",
    "babel-plugin-transform-es2015-modules-commonjs": "^6.16.0",
    "babel-plugin-transform-runtime": "^6.12.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-es2017": "^6.9.2",
    "babel-preset-stage-3": "^6.24.1",
    "expect": "^1.20.2",
    "glob": "^7.1.2",
    "jest": "^20.0.4"
}