V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐关注
Meteor
JSLint - a JavaScript code quality tool
jsFiddle
D3.js
WebStorm
推荐书目
JavaScript 权威指南第 5 版
Closure: The Definitive Guide
woshiyigexiaohao
V2EX  ›  JavaScript

webpack 如何实现提取.html 文件中的 script 和 style 标签? 并使用其他 loader 处理后生成文件地址?

  •  
  •   woshiyigexiaohao · 2020-11-26 10:18:17 +08:00 · 1827 次点击
    这是一个创建于 1219 天前的主题,其中的信息可能已经有所发展或是发生改变。

    有个需求是需要把.html 内的所有 script 标签 script:not([src]) 和 style 标签 使用对应的 loader 进行处理并将其变为文件引用形式.

    script 标签不同于 vue 可能存在 html 文件任何位置,可能需要经过 parse 处理.

    类似 Vue-loader

    第 1 条附言  ·  2020-11-26 15:58:57 +08:00

    参考大家的方式,最终得到了解决

    const root = parse(data.html)
    // 针对 script 进行 babel 处理
    root.querySelectorAll('script').forEach((script, index) => {
        if( !script.getAttribute('src') ) {
            script.set_content(
                require("@babel/core").transform(script.innerHTML, {
                    presets: ["@babel/preset-env"],
                    plugins: [
                        ['@babel/plugin-transform-modules-commonjs'],
                        ['@babel/plugin-transform-object-assign']
                    ]
                }).code
            )
        }
    })
    
    data.html = root.toString()
    cb(null, data)
    
    7 条回复    2020-11-26 12:11:13 +08:00
    woshiyigexiaohao
        1
    woshiyigexiaohao  
    OP
       2020-11-26 10:24:56 +08:00
    有啥思路嘛
    Torpedo
        2
    Torpedo  
       2020-11-26 10:28:52 +08:00
    @woshiyigexiaohao https://github.com/jantimon/html-webpack-plugin#configuration 可以把 html 当做模板,注入变量,拼最后生成的 html
    woshiyigexiaohao
        3
    woshiyigexiaohao  
    OP
       2020-11-26 10:36:29 +08:00
    @Torpedo plugins 晚于 loader 执行,如何在 plugin 中对文件运行 loader
    yaphets666
        4
    yaphets666  
       2020-11-26 10:57:45 +08:00
    原理嘛那肯定是正则匹配了,vue-loader 也是正则.
    Torpedo
        5
    Torpedo  
       2020-11-26 11:14:21 +08:00
    @woshiyigexiaohao 那就先写个解析 html 的 loader,把剩余的扔给后面的 js,styleloader 啥的。不知道 html-loader 行不
    KuroNekoFan
        6
    KuroNekoFan  
       2020-11-26 11:35:46 +08:00
    xpath 吧
    auroraccc
        7
    auroraccc  
       2020-11-26 12:11:13 +08:00   ❤️ 1
    找个 parse html 的库然后过 loader 拿到处理后的文件地址再替换就好了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3793 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 05:06 · PVG 13:06 · LAX 22:06 · JFK 01:06
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.