javascript - gulp-inject的使用方式
大家讲道理
大家讲道理 2017-04-10 16:16:30
[JavaScript讨论组]

关于gulp-inject的使用方式,今天使用gulp构建项目,使用到了gulp-inject自动插入静态文件到html,但是纠结啦。

正常的使用方式

<!DOCTYPE html>
<html>
<head>
  <title>My index</title>
  <!-- inject:css -->
  <!-- endinject -->
</head>
<body>

  <!-- inject:js -->
  <!-- endinject -->
</body>
</html>
var gulp = require('gulp');
var inject = require('gulp-inject');

gulp.task('index', function () {
  var target = gulp.src('./src/index.html');
  // It's not necessary to read the files (will speed up things), we're only after their paths:
  var sources = gulp.src(['./src/**/*.js', './src/**/*.css'], {read: false});

  return target.pipe(inject(sources))
    .pipe(gulp.dest('./src'));
});
<!DOCTYPE html>
<html>
<head>
  <title>My index</title>
  <!-- inject:css -->
  <link rel="stylesheet" href="/src/style1.css">
  <link rel="stylesheet" href="/src/style2.css">
  <!-- endinject -->
</head>
<body>

  <!-- inject:js -->
  <script src="/src/lib1.js"></script>
  <script src="/src/lib2.js"></script>
  <!-- endinject -->
</body>
</html>

但是有个问题,这样的话,他会把全部的js跟css文件添加上去,我现在想要的是,比如index.html页面,只单独引入index.js和index.css,其他的就是公用的引入在一起比如,comm.js comm.css等,我希望是这样:

<!DOCTYPE html>
<html>
<head>
  <title>My index</title>
  <!-- inject:css -->
  <link rel="stylesheet" href="/src/comm.css">
  <link rel="stylesheet" href="/src/index.css">
  <!-- endinject -->
</head>
<body>

  <!-- inject:js -->
  <script src="/src/comm.js"></script>
  <script src="/src/index.js"></script>
  <!-- endinject -->
</body>
</html>

我该怎么配置,或者该怎么写注解??真心求教。

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

全部回复(1)
大家讲道理

gulp-inject 也可以自定义标签,
你可以使用 starttag 配置

var sourcesIndex = gulp.src(['./src/**/index.js', './src/**/index.css'], {read: false});
var sourcesCommon = gulp.src(['./src/**/common.js', './src/**/common.css'], {read: false});

gulp.src('./src/index.html')
    .pipe(inject(sourcesIndex, {starttag: '<!-- inject:index:{{ext}} -->'}))
    .pipe(inject(sourcesCommon, {starttag: '<!-- inject:common:{{ext}} -->'}))
    .pipe(gulp.dest('./dist'));
<!DOCTYPE html>
<html>
<head>
  <title>My index</title>
  <!-- inject:common:css -->
  <!-- endinject -->

  <!-- inject:index:css -->
  <!-- endinject -->
</head>
<body>
  <!-- inject:common:js -->
  <!-- endinject -->

  <!-- inject:index:js -->
  <!-- endinject -->
</body>
</html>

请参考这个 https://github.com/klei/gulp-inject#method-1-use-gulp-injects-starttag-option

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号