如何将除JS、CSS、HTML以外的所有文件导入Webpack中作为资产?

jgovgodb  于 2023-04-21  发布在  Webpack
关注(0)|答案(1)|浏览(125)

我知道我可以使用Webpack在我的JS代码中导入资产(例如图像)。这对于在文件名中包含文件的哈希值很有用,因此我可以使用HTTP永久缓存资产

import cat from './cat.png'

export function CatGallery() {
    return <img src={cat} alt="A wonderful cat" />
}
//webpack.config.js
module.exports = {
  output: {
      assetModuleFilename: '[name].[contenthash][ext]',
  },

  module: 
      rules: [
        {
          test: /\.png$/,
          type: 'asset/resource'
        },
      ],
  }
};

不幸的是,我必须明确列出test regex中我的资产可以拥有的每个扩展。有没有一种方法可以编写一个regex,它可以覆盖除了与CSS,JS和HTML相关的所有文件?

olhwl3o2

olhwl3o21#

您可以使用与组中列出的 except 匹配的正则表达式修改配置。

//webpack.config.js
module.exports = {
  output: {
      assetModuleFilename: '[name].[contenthash][ext]',
  },

  module: 
      rules: [
        {
          test: /\.(?!(css|html|js|ts|jsx|tsx)$)[^.]+$/,
          type: 'asset/resource'
        },
      ],
  }
};

说明:

/
\. # match dot (escaped)
(?! # not followed by
    (css|html|js|ts|jsx|tsx) # any of these extensions
    $ # that are in the end. Prevents false matches like .ts.png 
)
[^.]+$ # the previous group didn't consume any input - we're still in place after dot. 
# The extension itself doesn't contain dots and must be at least one character, 
# and also should be the last in the filename
/

相关问题