vue-cli 3 编译时 css 放在 body 里

修改 vue.config.js

// https://stackoverflow.com/questions/58263664/vue-js-inject-styles-in-body-instead-of-head-of-index-html-webpack-htmlweb
class InjectStylesInBody {
  apply(compiler) {
    compiler.hooks.compilation.tap('inject-styles-in-body', (compilation) => {
      if (!compilation.hooks.htmlWebpackPluginAlterAssetTags) return
      compilation.hooks.htmlWebpackPluginAlterAssetTags.tap('inject-styles-in-body', function(pluginArgs) {
        const { head, body } = pluginArgs
        const styles = []
        head.filter(asset => asset.tagName === 'link' && asset.attributes && asset.attributes.rel === 'stylesheet')
          .forEach(asset => {
            head.splice(head.indexOf(asset), 1)
            styles.push(asset)
          })
        if (styles.length > 0) {
          // unshift 先加载样式, 再加载脚本 !
          // 先加载脚本可能会出现样式错误的问题 !
          body.unshift(...styles)
        }
      })
    })
  }
}

// vue.config.js
module.exports = {
    chainWebpack: config => {
      config
        .plugin('html')
        .tap(args => {
          args[0].inject = 'body'
          return args
        }).end()
        .plugin('inject-styles-in-body')
        .use(InjectStylesInBody).end()
    },
	...
}

posted on   正义的伙伴!  阅读(271)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
历史上的今天:
2020-01-13 vue-cli 3.x jsx 支持
2020-01-13 @SuppressWarnings() java warning 警告

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
//增加一段JS脚本,为目录生成使用
点击右上角即可分享
微信分享提示