Webpack - 用名称 + 哈希替换脚本标签“src”引用

如何解决Webpack - 用名称 + 哈希替换脚本标签“src”引用

这几天我一直在思考这个问题并在网上搜索,我一直找不到好的解决方案,所以我再次求助于 StackOverflow。

我接受了一个项目,我必须为旧网站堆栈配置 Webpack,该堆栈使用当前无法替换的非常古老和奇怪的模板引擎,但是我坚持至少能够使用 SCSS、ES6 和 Typescript (该站点也必须支持 IE11)。 由于有许多频繁更改的资产文件,该站点还必须使用某种缓存破坏功能。

我已经成功地使 webpack 配置输出 SCSS 到 CSS 文件,Typescript 编译,图像获取哈希名称,并保持模板 HTML 不受影响。 该代码直接在模板 HTML 代码中使用 <script>link 标记。

但是,当我尝试使用 html-loader<script> 标记的 src 属性替换为名称+哈希版本时遇到了问题。

程序没有处理我传递的入口文件,而是崩溃了,声称 Reference Error: document is not defined


ERROR in   Error: webpack-internal:///./js/test.js  :10
  var qs = document.querySelector.bind(do  cument);
           ^
  ReferenceError: document is not defined  
  - test.js:10 eval

这个问题也发生在我的 CSS 文件中,直到我从入口文件中删除它们并删除 MiniCssExtractPlugin,并简单地使用 file-loader

我不知道我是否可以对 JS/TS 文件做同样的事情,因为 Webpack 需要一个入口文件来执行它的包。说实话,我在入口文件中没有看到这一点,我只想使用 TS-loader 处理我的文件并输出为我可以参考的 ES5 兼容 JS。 当我尝试添加 file-loaderto myts-loader` 链时,它打破了诸如此类的抱怨:

Error: Prevent writing to file that only differs in casing or query string from already written file.
This will lead to a race-condition and corrupted files on case-insensitive file systems.

我的 webpack.config.js 如下:

var webpack = require('webpack');
var glob = require('glob');
var path = require('path');
const FixStyleOnlyEntriesPlugin = require("webpack-fix-style-only-entries");
const HtmlWebpackPlugin = require('html-webpack-plugin');

//Generate object for webpack entry
var entryObjectJS = glob.sync('./js/*.[tj]s').reduce(
    function (entries,entry) {
        var matchForRename = /^\.\/js\/(?:[\w\d_-]+\/)*([\w\d\-\.]+)+.(ts|js)$/g.exec(entry);
        console.log(matchForRename);
        if (matchForRename !== null && typeof matchForRename[1] !== 'undefined') {
            entries[matchForRename[1]] = entry;
        }
        return entries;
    },{}
);

module.exports = {
  target: "node",mode: `development`,devtool: "eval-source-map",target: ['web','es5'],entry: { ...entryObjectJS},output: {
      path: path.resolve(__dirname,'../static/compedWEBPACK/dist'),filename: 'js/[name].js?[chunkhash:6]',},watchOptions: {
    aggregateTimeout: 600,ignored: /node_modules/,module: {
    rules: [
      {
        test: /\.(html|tt)$/,use: {
          loader: 'html-loader',options: {
            minimize: false,attributes: {
              list: [
                // All default supported tags and attributes
                {
                  tag: 'img',attribute: 'src',type: 'src',{
                  tag: 'img',attribute: 'data-src',attribute: 'data-srcset',type: 'srcset',{
                  tag: 'link',attribute: 'href',{
                  tag: 'script',],{
        test: /\.s[ac]ss$/i,use: [
             {
          loader: 'file-loader',options: {
              name: "[name].css?[hash:6]",outputPath: "css",publicPath: "../css" // depends on your project architecture
          }
      },'extract-loader',/** Compiled CSS gets turned into CommonJS code */
        {
          loader: 'css-loader',options:
          {
            sourceMap: true,}
        },'resolve-url-loader',/** Resolves relative addresses from SASS imports */
        {
          loader: `sass-loader`,options: {              
            sourceMap: true,}
        }
      ]
    },{
      test: /\.(jpe?g|png|gif|woff|woff2|eot|ttf|svg)(\?[a-z0-9=.]+)?$/,use: {
          loader: 'file-loader',// this need file-loader
          options: {
            name: "[name].[ext]?[hash:6]",outputPath: "comp_images",publicPath: '../comp_images',}
      }
  },// Include ts,tsx,js,and jsx files.
  {
      test: /\.(ts|js)x?$/,exclude: /node_modules/,use: [
          {
            loader: 'file-loader',options: {
                name: "[name].js?[hash:6]",outputPath: "js",publicPath: "../js"
            },{
          loader: 'ts-loader',}
        ] 
      },]
  },resolve: {
    mainFields: ['browser','main'],extensions: [ '.tsx','.ts','.js','.json'],optimization: {
    // noEmitOnErrors : true
  },plugins: [
    new FixStyleOnlyEntriesPlugin(),new HtmlWebpackPlugin({
    filename: "comp_template/testpage.tt",template: "template/testpage.tt",inject: false,}),new HtmlWebpackPlugin({
    filename: "comp_template/ranking.tt",template: "template/ranking.tt",new HtmlWebpackPlugin({
    filename: "comp_template/detail.tt",template: "template/detail.tt",})
  ]
};

我的文件夹布局如下:

webpack-project
 ┣ ?image
 ┃ ┣ ?path
 ┃ ┃ ┗ ?to
 ┃ ┃ ┃ ┗ ?Mountain.png
 ┃ ┣ ?Mountain.svg
 ┃ ┣ ?elmo.jpg
 ┃ ┗ ?miniyoda.jpeg
 ┣ ?js
 ┃ ┣ ?modules
 ┃ ┃ ┣ ?markdown.js
 ┃ ┃ ┗ ?testmodule.js
 ┃ ┣ ?global.js
 ┃ ┣ ?test.js
 ┣ ?style
 ┃ ┣ ?modules
 ┃ ┃ ┣ ?path
 ┃ ┃ ┃ ┗ ?to
 ┃ ┃ ┃ ┃ ┗ ?image_import_test.scss
 ┃ ┃ ┗ ?tailwind.css
 ┃ ┣ ?pages
 ┃ ┣ ?partials
 ┃ ┃ ┗ ?_partial.scss
 ┃ ┣ ?page2style.scss
 ┃ ┗ ?style.scss
 ┣ ?template
 ┃ ┣ ?detail.tt
 ┃ ┣ ?ranking.tt
 ┃ ┗ ?testpage.tt

我想要的输出目录样式:

?compedWEBPACK
 ┗ ?dist
 ┃ ┣ ?comp_images
 ┃ ┃ ┣ ?Mountain.png
 ┃ ┃ ┣ ?Mountain.svg
 ┃ ┃ ┣ ?elmo.jpg
 ┃ ┃ ┗ ?miniyoda.jpeg
 ┃ ┣ ?comp_template
 ┃ ┃ ┣ ?detail.tt
 ┃ ┃ ┣ ?index.tt
 ┃ ┃ ┣ ?ranking.tt
 ┃ ┃ ┗ ?testpage.tt
 ┃ ┣ ?css
 ┃ ┃ ┣ ?page2style.css
 ┃ ┃ ┗ ?style.css
 ┃ ┗ ?js
 ┃ ┃ ┣ ?global.js
 ┃ ┃ ┣ ?global1.js
 ┃ ┃ ┣ ?runtime~global.js
 ┃ ┃ ┣ ?runtime~test.js
 ┃ ┃ ┣ ?runtime~test22.js
 ┃ ┃ ┣ ?test.js
 ┃ ┃ ┣ ?test1.js
 ┃ ┃ ┣ ?test22.js
 ┃ ┃ ┗ ?test221.js

我想要的输出:

<body>
    <h1>TEMPLATE Test page for Webpack </h1>

    <img src="../comp2_images/elmo.jpg?89a3c0" alt="elmo" srcset=""/>
    <img src="../comp2_images/Mountain.png?3217ee" alt="mountainsss" srcset=""/>

    <div class="img-import-test"></div>
    <link rel="stylesheet" href="../css/page2style.css?ce38b8" />
    <link rel="stylesheet" href="../css/style.css?5582d2" />
    <script>
        [% In code value %]
        console.log(`[%PLEASE WORK %]`);
        [% SUCH IS LIFE %]
    </script>

    <script src="../js/global.js?546ec4"></script>
    <script src="../js/test.js?de178a"></script>
    <script src="../js/test22.js?1576a"></script>
</body>

请注意,这些脚本标记引用已经存在,我只是想让 Webpack 像对 SCSS 文件所做的那样对其进行转换和添加哈希,然后编译、重命名文件夹并将哈希添加到其中。

我自己对 Webpack 配置还很陌生,所以我可能做错了一些事情,并想就如何最好地处理我的用例提供一些建议。

谢谢。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res