【问题标题】:Remove scripts from index.html through gulp通过 gulp 从 index.html 中删除脚本
【发布时间】:2014-07-10 07:54:55
【问题描述】:

我在我们的应用程序中使用 gulp,我们在 Gulpfile.js 中有 2 个流,一个用于生产,第二个用于开发,但我不想保留 2 个 index.html 文件,例如index.html 和 index.dev。 html,我想要一个 index.html 文件,但是对于生产版本,我有不需要的脚本,例如。

 <!--dev depends -->
    <script src="angular-mocks/angular-mocks.js"></script>
    <script src="server.js"></script>
 <!--dev depends -->

问题是:如何通过 Gulp 从 html 中删除某些内容

【问题讨论】:

    标签: javascript angularjs gulp


    【解决方案1】:

    您可以使用专门用于此特定目的的 gulp-html-replace 插件:

    https://www.npmjs.org/package/gulp-html-replace

    【讨论】:

      【解决方案2】:

      您可以采用稍微不同的方法:模板化您的 index.html 并使用 gulp-template 插件在您的构建中处理模板:

      var template = require('gulp-template');
      
      //production task 
      gulp.task('prod', function () {
          return gulp.src('src/index.html').pipe(template({
              scripts : []
          })).pipe(gulp.dest('dist'));
      });
      
      
      //dev task
      gulp.task('prod', function () {
          return gulp.src('src/index.html').pipe(template({
              scripts : ['angular-mocks/angular-mocks.js', 'server.js']
          })).pipe(gulp.dest('dist'));
      });
      

      你的index.html 可以变成这样的模板:

      &lt;% _.forEach(scripts, function(name) { %&gt;&lt;script src="&lt;%- name %&gt;" type="text/javascript"&gt;&lt;/script&gt;&lt;% }); %&gt;

      当然,您可以编写自己的插件/传递流,从 index.html 中删除脚本,但这需要实际解析/重写 index.html。就我个人而言,我发现基于模板的解决方案更易于实施且更“优雅”。

      【讨论】:

      • "你可以稍微接近 is" 我相信is 应该是it。我说的对吗?
      猜你喜欢
      • 2021-05-17
      • 2018-01-12
      • 1970-01-01
      • 1970-01-01
      • 2015-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-24
      相关资源
      最近更新 更多