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

时间:2021-01-20 17:35:39

标签: javascript typescript webpack script-tag webpack-html-loader

这几天我一直在思考这个问题并在网上搜索,我一直找不到好的解决方案,所以我再次求助于 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',
                  type: 'src',
                },
                {
                  tag: 'img',
                  attribute: 'data-srcset',
                  type: 'srcset',
                },
                {
                  tag: 'link',
                  attribute: 'href',
                  type: 'src',
                },
                {
                  tag: 'script',
                  attribute: 'src',
                  type: 'src',
                },
              ],
            },
          },
        },
        
      },
      {
        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",
    inject: false,
  }),
  new HtmlWebpackPlugin({
    filename: "comp_template/detail.tt",
    template: "template/detail.tt",
    inject: false,
  })
  ]
};

我的文件夹布局如下:

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 配置还很陌生,所以我可能做错了一些事情,并想就如何最好地处理我的用例提供一些建议。

谢谢。

0 个答案:

没有答案