简体   繁体   中英

Gulp Babel Async/Await

Trying to minify a file and run it directly on the browser.

I'm using gulp & babel to do. The problem relies when I try to use async/await functions.

package.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",
    ...
}

The file

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

Gulp/Babel config

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));

This simply threw "regeneratorRuntime is not defined".

So I've tried adding "@babel/plugin-transform-runtime".

Gulp/Babel config

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));

But now I get "require is not defined".

Does any one have any clues on how to achieve this?

You're almost there! I had a similar issue, the problem is that the compiled Gulp code includes "require" statements which aren't supported in most browsers. What fixed the issue for me was to add Webpack to the Gulp workflow to bundle everything:

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

in your 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;

You also need to add a Webpack config file: webpack.config.js

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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