gpt4 book ai didi

javascript - 如何使用webpack html插件在头部注入(inject)css包和在体内注入(inject)js包

转载 作者:行者123 更新时间:2023-11-30 06:55:12 24 4
gpt4 key购买 nike

我绝对不是Webpack的新手,我在一个小项目上使用scss和vue。
我想做的是将我所有的.scss文件编译为css,并将它们 bundle 在bundle.css中,然后将其自动注入(inject)到头部(我已经设置了sass和css加载程序,将 bundle 文件归档到css中)。但是我也希望将我的vue app.js包放在主体的末尾,也由htmlWebpackPlugin注入(inject)(已经完成)。
使用单个HtmlWebpackPlugin将所有内容都放入我的index.html中,将使我的 body 样式或头部的javascript保持不变。

我的第一个猜测是,我必须定义2个Plugin-Instances

var jsInjectorPlugin = new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.html',
inject: 'body'
});
var cssInjectorPlugin = new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.html',
inject: 'head'
})

但是我如何告诉webpack,将第一个插件用于CSS,将另一个用于JS?由于我没有像加载程序那样的 test,所以我不知道该怎么做

因此,这个问题的重点是,有人可以向我解释我如何实现将css-bundle注入(inject)头部而将js-bundle注入(inject)体内吗?
(赞赏如何在webpack-config中执行此操作的代码段)

最佳答案

您需要HtmlWebpackInjector

  • 它与HtmlWebpackPlugin一起使用,只需在块名称中添加_head,即可自动将块插入头部。
  • const HtmlWebpackPlugin = require('html-webpack-plugin');
    const HtmlWebpackInjector = require('html-webpack-injector');

    module.exports = {
    entry: {
    index: "./index.ts",
    // add "_head" in the bundle name to inject in head.
    // use sass and css loaders to compile sass to js bundle.
    bundle_head: "./index.scss"
    },
    output: {
    path: "./dist",
    filename: "[name].bundle.js"
    },
    plugins: [
    new HtmlWebpackPlugin({
    template: "./index.html",
    filename: "./dist/index.html",
    chunks: ["index", "bundle_head"]
    }),
    new HtmlWebpackInjector()
    ]
    }

    这会自动将 index块注入(inject)html文档的正文,并将 bundle_head注入(inject)html文档的头部。最终的html看起来像:
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>Archit's App</title>
    <script type="text/javascript" src="bundle_head.bundle.js"></script> <--injected in head
    </head>
    </head>
    <body>
    <script src="index_bundle.js"></script> <--injected in body
    </body>
    </html>

    关于javascript - 如何使用webpack html插件在头部注入(inject)css包和在体内注入(inject)js包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46202546/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com