首页 > 解决方案 > 如何将 css 直接注入到我的 index.html 中?

问题描述

我正在尝试连接外部 css 和 js 文件(从我的 index.html 文件中引用),然后将它们直接放入我的 html 文件中。我知道如何连接然后将它们放入一个文件中。但还没有设法将它们直接写入我的 index.html。如果我使用注入,那么它不会从 index.html 中获取引用。我的项目需要尽可能少的文件,所以我需要将所有代码粘贴到一个 html 文件中。任何人都可以回答我吗?

吞咽代码:

gulp.task('useref', function(){
    gulp.src(src/index.html)
        .pipe(useref())
        .pipe(gulpIf('*.js', uglify()))
        .pipe(gulpIf('*.css', modifyCssUrls({
          modify: function (url, filePath) {
            var splitted = url.split('/');
            return splitted[splitted.length - 1];
          },
          prepend: '',
          append: ''
        })))
        .pipe(gulp.dest('./tmp'));
});

运行 gulp 之前的 index.html

<!-- css -->
<!--build:css main.css -->
<link rel="stylesheet" type="text/css" href="../../../assets/css/shared.css">
<link rel="stylesheet" type="text/css" href="../assets/css/main.css">
<!-- endbuild -->

<!--build:js main.min.js -->
<script type="text/javascript" src="../../../assets/js/fontfaceobserver.js"></script>
<script type="text/javascript" src="../../../assets/js/SplitText.js"></script>
<!-- endbuild -->

运行 gulp 后的 index.html

<!-- css -->
<link rel="stylesheet" href="main.css">

<script src="main.min.js"></script>

所以我希望它实际上将 css 粘贴到我的 html 文件中,如下所示:

<!-- css -->
<style>
@font-face {
  font-family: 'circular-pro-black';
  src: url("circular-pro-black.woff2") format('woff2'),
         url("circular-pro-black.woff") format('woff');
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 'circular-pro-bold';
  src: url("circular-pro-bold.woff2") format('woff2'),
         url("circular-pro-bold.woff") format('woff');
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 'anchor-bold';
  src: url("anchor-bold.woff2") format('woff2'),
         url("anchor-bold.woff") format('woff');
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 'anchor-semibold';
  src: url("anchor-semibold.woff2") format('woff2'),
         url("anchor-semibold.woff") format('woff');
  font-weight: normal;
  font-style: normal;
}
</style>



<script>
and the js content here
</script>

标签: gulpgulp-useref

解决方案


推荐阅读