面试题答案
一键面试以下是在 webpack.config.js
中针对不同格式图片优化加载并配置不同环境策略的示例:
-
安装必要的 loader:
- 确保安装
url-loader
和file-loader
:
npm install url-loader file-loader --save-dev
- 确保安装
-
配置
webpack.config.js
:const path = require('path'); module.exports = (env) => { const isProduction = env === 'production'; const fileLoaderRule = { test: /\.(png|jpg|jpeg|gif)$/i, use: [ { loader: 'url-loader', options: { limit: 8192, // 将小于 8kb 的图片转为 base64 name: isProduction? 'images/[name].[contenthash].[ext]' : 'images/[name].[ext]', publicPath: isProduction? '../' : '/' } } ] }; const svgLoaderRule = { test: /\.svg$/i, issuer: /\.[jt]sx?$/, use: ['@svgr/webpack'] }; return { entry: './src/index.js', output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.js' }, module: { rules: [fileLoaderRule, svgLoaderRule] } }; };
在上述配置中:
fileLoaderRule
:针对png
、jpg
、jpeg
、gif
图片格式,url-loader
在图片小于8kb
时会将其转为base64
编码。- 在生产环境中,
name
属性设置图片输出路径为images/[name].[contenthash].[ext]
,通过contenthash
确保缓存控制。 - 在开发环境中,
name
属性设置为images/[name].[ext]
。 publicPath
根据环境设置图片的公共路径。
- 在生产环境中,
svgLoaderRule
:使用@svgr/webpack
处理svg
文件,issuer: /\.[jt]sx?$/
确保仅在 JavaScript/TypeScript 文件导入svg
时应用此 loader。