如何使用webpack在React中加载本地视频? [英] How to load a local video in React using webpack?
问题描述
我似乎无法弄清楚如何从本地文件中获取html5视频以在react应用中呈现.从字面上看,我能够做到这一点的唯一方法是这样的:
I can't seem to figure out how to get an html5 video to render in a react app from local files. Literally the only way I've been able to get this to work is like this:
<video src="http://www.w3schools.com/html/movie.mp4" controls />
这是我尝试过的
1..直接包含路径
<video src={require('path/to/file.mp4')} controls />
返回错误
Module parse failed: /path/to/file.mp4 Line 1: Unexpected token ILLEGAL
You may need an appropriate loader to handle this file type.
2..一次将这些加载程序添加到webpack配置中
2. Adding these loaders one at a time to the webpack config
{
test: /\.(mp4)$/,
loader: 'file'
// loader: 'url-loader'
// loader: 'url-loader?limit=100000'
// loader: 'file-loader'
// loader: 'file-loader?name=videos/[name].[ext]'
},
这会在浏览器中吐出以下错误
this spit out the following error in the browser
GET http://localhost:3000/530c2bf99dad0f857d46940b62b84946.mp4 404 (Not Found)
3..我尝试将直接网址添加到文件中
3. I tried adding a direct url to the file
<video src={require('http://localhost:3000/path/to/file.mp4')} controls />
但仍然存在错误:
Module not found: Error: Cannot resolve module 'http://localhost:3000/path/to/file.mp4' in path/to/file.mp4
4..我尝试在我的Webpack配置中添加mp4扩展名像这个人一样
4. I tried adding the mp4 extension in my webpack config like this person did
{
test: /\.jpe?g$|\.gif$|\.png$|\.ico|\.svg$|\.woff$|\.ttf$|.mp4$/,
loader: 'url-loader?limit=8192'
}
但没有运气
5..我开始实施 webpack-isomorphic-tools ,但是我不确定这是否是正确的方向,所以我停了下来.好像这个人以这种方式工作了. (查看文件)
5. I started implementing webpack-isomorphic-tools but then I wasn't sure if this was the right direction so I paused on it. It seems like this guy got it working this way. (see file)
我还在webpack文档中的加载程序约定下注意到,file-loader
将加载视频文件.
这是否意味着webpack不会加载其他视频类型,例如.mov, .vob, .avi, etc.
?
I also noticed in the webpack documentation under loader conventions that file-loader
will load video files.
Does this mean webpack won't load other video types such as .mov, .vob, .avi, etc.
?
如果您想看一下代码,请这是存储库.
If you want to take a look at the code, here's the repository.
资源
- Webpack Docs: Loader Conventions
- Add a WebM and MP4 loader to the default Webpack config
- Loading mp4 video in to
video
tag w/ File loader - Unable to load resources via file-loader
推荐答案
我遇到了同样的问题,我的解决方法是:
I had the same problem, my solution is:
它使用 https://github.com/webpack/html-loader 和 https://github.com/webpack/url-loader :
装载机配置:
loaders: [{
test: /\.html$/,
loader: 'html-loader?attrs[]=video:src'
}, {
test: /\.mp4$/,
loader: 'url?limit=10000&mimetype=video/mp4'
}]
在html中:
一个简单的视频标签,remeber webpack使用了指向html文件的路径.
A simple video tag, remeber webpack uses path referenced to the html file.
<video src="../../../assets/videos/cover1.mp4"></video>
这对我有用.
参考: https://github.com/webpack/html-loader/issues/28
这篇关于如何使用webpack在React中加载本地视频?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!