使用gulp构建网站

206 阅读2分钟
项目只有十几个页面,大多静态,表单较少,交互也少,开发构架的逻辑简单
开发方面:vue或react的虚拟dom此时不能发挥其长处还显得笨重,那就jq
构建方面:webpack大材小用了,那就玩一玩流水线task的gulp

1、页面公共部分 gulp-file-include

将公共部分(header等)分离成组件,此插件能使指定文件注入到指定位置(将文件内容当做字符串,js处理字符串实现)

html中:
<p>插入之前的行</p>
@@include('components/header.html')
<p>插入之后的行</p>
./components/header.html中: 
<p>公共的部分</p>
gulpfile:
.pipe(fileinclude({
    prefix'@@',
    basepath'@file'
  }))
结果:
<p>插入之前的行</p>
<p>公共的部分</p>
<p>插入之后的行</p>

2、模板引擎 art-template

没有v-for、v-if,需要动态拼接html插入文档? 眼前开始悬浮左右尖括号和单双引号,不, art-template基于模板生成html渲染字符串, 可在页面cdn引入(建议下载到本地,打包时与其他库文件打包到一起)

页面直接:
<script type="text/html" id="templateTypeList">
  {{each list as item}}
  {{if item.day == 'tomorrow'}}
  <p>就是任性</p>
  {{else}}
  <p>你你你你要跳舞吗</p>
  {{/if}}
  {{/each}}
</script>
js中:
  var typeProductListHtml = template('templateTypeList', { list: [] });
  var dom = document.getElementById('typeProductList');
  dom.innerHTML = typeProductListHtml;

继续愉快的玩耍

3、更换主题色 gulp-less/gulp-sass

定义一个theme.less和不同的 themeType.less, 此方法很笨求推荐

const themeType = global.gTheme; // 全局主题色类型 light/dark
// 每次更改完主体配置 更改引入主体路径
gulp.task('theme', async function () {
    const text = `@import './${themeType}.less';`;
    fs.writeFile('less/theme/index.less', text, 'utf-8', function (err) {
        if (err) {
            console.log('写入文件失败:', err);
        }
    });
});
// 开发时 watch .less文件的更改less()转下
// 不同主体对应背景图更改同上

4、 启动服务 gulp-webserver/browser-sync

没有webpack-dev-server怎么办? 可用这两,启动本地服务类似, 开发更改时自动刷新页面,同一局域网手机可访问调试

5、打包使用推荐

将所有需要使用到的文件打包到./dist下面

html: gulp-htmlmin, gulp-processhtml,gulp-htmlmin
css: gulp-minify-css,
js: gulp-jshint,gulp-uglify...
del, gulp-clean: 删除
gulp-concat: 文件合并
gulp-replace: 字符串替换
gulp-html-replace: html文件中注释内的link或script用配置项替换(用总的vendor.css等替换到开发时分散开来的文件)
gulp-inject: 注入外部文件 

6、文件名后加版本号随机数等

否则更新版本时浏览器缓存机制可能导致部分文件使用缓存,页面乱掉