【问题标题】:How do I disable babel minification when not in production?如何在不生产时禁用 babel 缩小?
【发布时间】:2017-10-02 11:56:59
【问题描述】:

我通过 gulp 使用 babelifybabili 进行 JS 缩小:

// Now run the watchifys function for this bundle
watchifysForBundle[jsBundle]
    // Note: we don't use any babel presets - instead we just write code in what evergreen browsers support
    .transform(babelify, {
        presets: ['babel-preset-babili'],
        ignore: ['buffer']
    })

但是我似乎找不到如何通过选项来检查 NODE_ENV 并在不生产时禁用 babelibabelify docs 似乎没有帮助,即使是这种常见的用例。

如何在不生产时禁用 babelify 缩小?

【问题讨论】:

    标签: babeljs minify babelify


    【解决方案1】:

    Babili 已被弃用,并已重命名为 babel-minify,因此您应该改用它。

    npm install babel-preset-minify --save-dev
    

    要禁用开发中的缩小,您根本不要使用babel-preset-minify(或babel-preset-babili)。当您使用 Gulp 时,您可以使用 Node.js 提供的所有内容来决定要包含哪些预设,这意味着您可以检查 process.env.NODE_ENV 并决定是否要包含 minify 预设。

    watchifysForBundle[jsBundle]
        .transform(babelify, {
            presets: process.env.NODE_ENV === 'production' ? ['minify'] : [],
            ignore: ['buffer']
        })
    

    另一种方法是使用Babel's env option(不要与babel-preset-env 混淆),如果未定义BABEL_ENV,则使用与BABEL_ENVNODE_ENV 的值匹配的配置。这种方法见babel-preset-minify - Usage

    {
      "env": {
        "production": {
          "presets": ["minify"]
        }
      }
    }
    

    env 选项不是很推荐,主要是因为.babelrc 是 JSON,没有很好的方法来定义条件配置。这将在 Babel 7 中发生变化,它允许 .babelrc.js 配置,您可以在其中拥有 Node.js 的全部功能,这意味着您可以做与 Gulp 相同的事情。

    【讨论】:

    • 谢谢!重命名还解释了为什么我很难找到文档!
    【解决方案2】:

    为避免缩小,请勿使用 uglify

    gulp.task('build:js', function(){
        return browserify(
             'test.js'
        )
        .transform('babelify',{
          presets: ['@babel/preset-env']
        })
        .bundle()
        .pipe(source('test.js'))
        .pipe(buffer())
        .pipe(uglify())
        .pipe(gulp.dest('destpath'));
    });
    

    改为尝试---在 babelify 中添加 option-compact:false, global:true

    gulp.task('build:js', function(){
        return browserify(
             'test.js'
        )
        .transform('babelify',{
          presets: ['@babel/preset-env'],
          compact: false,
          global: true
        })
        .bundle()
        .pipe(source('test.js'))
        .pipe(buffer())
        .pipe(gulp.dest('destpath'));
    });
    

    【讨论】:

      猜你喜欢
      • 2012-03-29
      • 2017-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-15
      • 2012-08-10
      相关资源
      最近更新 更多