使用Webpack无法导入MP4文件,配置Loader后仍报错求助
Webpack导入MP4文件报错:无Loader配置处理该文件
问题情况
- 导入MP4的代码:
import videoSrcInit from '../src/ImageSlider/slider_1.mp4'; - 报错提示:无Loader配置处理该文件
- 已尝试操作:参考方案在
webpack.config.js中添加了file-loader配置处理mov/mp4文件,但问题仍未解决。当前webpack.config.js配置如下:
const path = require('path'); module.exports = { entry: './src/index.js', output: { filename: 'main.js', path: path.resolve(__dirname, 'dist'), assetModuleFilename: '[name][ext]', }, module: { rules: [ { test: /\.css$/i, use: ['style-loader', 'css-loader'], }, { test: /\.(pdf|png|svg|jpg|jpeg|gif)$/i, type: 'asset/resource', }, { test: /\.(woff|woff2|eot|ttf|otf)$/i, type: 'asset/resource', }, { test: /\.(mov|mp4)$/, use: [ { loader: 'file-loader', options: { name: '[name].[ext]' } } ] }, { test: /\.html$/, exclude: /node_modules/, use: [ { loader: "html-loader", options: { sources: { list: [ { tag: "source", attribute: "src", type: "src" } ] } } } ] } ] } };
解决办法
你用的是Webpack 5,它自带的Asset Modules已经替代了file-loader这类工具,两者同时使用可能出现冲突,导致配置不生效。按下面步骤调整:
卸载file-loader(如果已经安装)
npm uninstall file-loader --save-dev修改webpack配置,把mov/mp4的规则改成和图片、字体一致的
asset/resource类型:{ test: /\.(mov|mp4)$/i, type: 'asset/resource' }检查导入路径:确认
../src/ImageSlider/slider_1.mp4这个路径是正确的,文件确实存在于对应位置。清理缓存并重新构建
执行构建命令前,先删除dist目录和Webpack缓存,避免旧配置影响:rm -rf dist npm run build
修改后的完整webpack.config.js规则部分:
module: { rules: [ { test: /\.css$/i, use: ['style-loader', 'css-loader'], }, { test: /\.(pdf|png|svg|jpg|jpeg|gif)$/i, type: 'asset/resource', }, { test: /\.(woff|woff2|eot|ttf|otf)$/i, type: 'asset/resource', }, { test: /\.(mov|mp4)$/i, type: 'asset/resource' }, { test: /\.html$/, exclude: /node_modules/, use: [ { loader: "html-loader", options: { sources: { list: [ { tag: "source", attribute: "src", type: "src" } ] } } } ] } ] }
内容的提问来源于stack exchange,提问作者Miclaine Elise
相关产品推荐
相关产品推荐

