繁体   English   中英

Gulp Babel 异步/等待

[英]Gulp Babel Async/Await

尝试缩小文件并直接在浏览器上运行它。

我正在使用 gulp 和 babel 来做。 当我尝试使用 async/await 函数时,问题取决于。

包.json

{
    "@babel/core": "^7.11.6",
    "@babel/plugin-transform-async-to-generator": "^7.12.1",
    "@babel/plugin-transform-runtime": "^7.12.1",
    "@babel/preset-env": "^7.11.5",
    "gulp": "^4.0.2",
    "gulp-babel": "^8.0.0",
    "gulp-concat": "^2.6.1",
    ...
}

文件

const i = async () => {
    return await fetchAll();
};

Gulp/Babel 配置

const BabelConfig = {
    presets: ['@babel/env'],
    plugins: ['@babel/plugin-transform-async-to-generator']
};
const imports = ['./dev/**.*.js'];
return gulp.src(imports)
    .pipe(babel(BabelConfig))
    .pipe(concat('min.js'))
    .pipe(gulp.dest(paths.dist.js));

这只是抛出“未定义 regeneratorRuntime”。

所以我尝试添加“@babel/plugin-transform-runtime”。

Gulp/Babel 配置

const BabelConfig = {
    presets: ['@babel/env'],
    plugins: ['@babel/plugin-transform-async-to-generator', '@babel/plugin-transform-runtime']
};
const imports = ['./dev/**.*.js'];
return gulp.src(imports)
    .pipe(babel(BabelConfig))
    .pipe(concat('min.js'))
    .pipe(gulp.dest(paths.dist.js));

但现在我得到“需要未定义”。

有没有人有任何关于如何实现这一目标的线索?

您快到了! 我有一个类似的问题,问题是编译的 Gulp 代码包含大多数浏览器不支持的“require”语句。 对我来说解决问题的是将 Webpack 添加到 Gulp 工作流程以捆绑所有内容:

npm install --save-dev webpack webpack-cli webpack-stream

在你的 gulpfile.js 中:

const {src, dest, watch} = require('gulp');
const gulpBabel = require('gulp-babel');
const webpack = require('webpack-stream');
const compiler = require('webpack');

function myES6Transpiler() {
    return src('./es6/utilities.js')
        .pipe(gulpBabel({
            presets: ['@babel/preset-env', 'babel-preset-minify'],
            plugins: ['@babel/transform-runtime', '@babel/plugin-transform-async-to-generator'],
        }))
        .pipe(webpack(require('./webpack.config-util.js'), compiler, function (err, stats) {
            /* Use stats to do more things if needed */
        }))
        .pipe(dest('./js/'))
}

exports.myES6Transpiler = myES6Transpiler;

您还需要添加一个 Webpack 配置文件:webpack.config.js

module.exports = {
    mode: "production",
    output: {
        filename: "utilities.js"
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM