美文网首页
gulp打包入门问题

gulp打包入门问题

作者: 昊哇恰 | 来源:发表于2020-05-11 23:54 被阅读0次

入门常见问题

/*
*  js文件打包
*  package.json
*  babel 转换es6到es5 (gulp只能打包es5文件) 
*  需要得依赖 gulp-babel , babel , babel-cli , @babel/core(替代babel-core) , @babel/preset-env(替代babel-preset-env) 
*  由于gulp-babel是最新版本得 所以需要把依赖替换成和 gulp-babel匹配得依赖
/*
 "devDependencies": {
    "@babel/core": "^7.9.6",
    "@babel/preset-env": "^7.9.6",
    "babel": "^6.23.0",
    "babel-cli": "^6.26.0",
    "babel-preset-env": "^1.7.0",
    "babel-preset-es2015": "^6.24.1",
    "gulp": "^4.0.2",
    "gulp-babel": "^8.0.0", //npm下载得最新版本 需要和最新版本得@babel/core和 @babel/preset-env匹配
    "gulp-rename": "^2.0.0",
    "gulp-htmlmin": "^5.0.1",
    "gulp-cssmin": "^0.2.0",
    "gulp-autoprefixer": "^7.0.1",
    "gulp-uglify": "^3.0.2"
  }
}
  • 我们还需要在根目录下设置.babelrc得转换形式
// .babelrc
{
    "presets": [
        "env"
    ]
}
  • 看了网上好多帖子,说是用gulp-babel@7 v7.0.1 但是我试了很多次,在看到一篇文章之后提到依赖不匹配,突然想到 用新的v8.0.0版本得gulp-bael 应该使用匹配得babel。
/*
*  css文件打包 需要用到gulp-cssmin压缩css文件 gulp-autoprefixer 增加浏览器兼容前缀(这个好~)
*/
"devDependencies": {
    "@babel/core": "^7.9.6",
    "@babel/preset-env": "^7.9.6",
    "babel": "^6.23.0",
    "babel-cli": "^6.26.0",
    "babel-preset-env": "^1.7.0",
    "babel-preset-es2015": "^6.24.1",
    "gulp": "^4.0.2",
    "gulp-autoprefixer": "^7.0.1", //  增加兼容前缀
    "gulp-babel": "^8.0.0",
    "gulp-cssmin": "^0.2.0", // 压缩css文件 compressed格式
    "gulp-rename": "^2.0.0",
    "gulp-uglify": "^3.0.2"
  }
/*
* 在调用autoprefixer的时候 由于版本是新的 所以我们又有了新的书写方式
*/
 .pipe(autoprefixer({
            overrideBrowserslist: [
                "Android 4.1",
                "iOS 7.1",
                "Chrome > 31",
                "ff > 31",
                "ie >= 8"
            ],
            grid: true
        }))
  • 压缩html
/*
* 插件名称 gulp-htmlmin
* 1.collapseWhitespace:从字面意思应该可以看出来,清除空格,压缩html,这一条比较重要,
 作用比较大,引起的改变压缩量也特别大;
* 2.collapseBooleanAttributes:省略布尔属性的值,比如:<input checked="checked"/>,
 那么设置这个属性后,就会变成 <input checked/>;
* 3.removeComments:清除html中注释的部分,我们应该减少html页面中的注释。
* 4.removeEmptyAttributes:清除所有的空属性,
* 5.removeSciptTypeAttributes:清除所有script标签中的Type=`text/javascript`属性。
* 6.removeStyleLinkTypeAttributes:清楚所有Link标签上的Type属性。
* 7.minifyJS:压缩html中的javascript代码。
* 8.minifyCSS:压缩html中的css代码。
*/
 .pipe(htmlmin({
            //合并空格
            collapseWhitespace: true,
            collapseBooleanAttributes: false,
            removeComments: true,
            removeEmptyAttributes: true,
            removeScriptTypeAttributes: false,
            removeStyleLinkTypeAttributes: false,
            minifyJS: true,
            minifyCSS: true
        }))

相关文章

网友评论

      本文标题:gulp打包入门问题

      本文链接:https://www.haomeiwen.com/subject/yxpmnhtx.html