【问题标题】:Gulp Babel Async/AwaitGulp Babel 异步/等待
【发布时间】:2021-01-31 22:06:05
【问题描述】:

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

我正在使用 gulp & babel 来做。当我尝试使用 async/await 函数时,问题就出现了。

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

文件

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 is not defined”。

所以我尝试添加“@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));

但现在我得到“require is not defined”。

有没有人知道如何做到这一点?

【问题讨论】:

    标签: javascript async-await gulp ecmascript-2016


    【解决方案1】:

    你快到了!我有一个类似的问题,问题是编译的 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"
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-18
      • 1970-01-01
      • 2016-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      相关资源
      最近更新 更多