Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

reactjs - How to load a local video in React using webpack?

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 />

Here's what I've tried

1. Including the path directly

<video src={require('path/to/file.mp4')} controls />

which returns an error

Module parse failed: /path/to/file.mp4 Line 1: Unexpected token ILLEGAL
You may need an appropriate loader to handle this file type.

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. I tried adding a direct url to the file

<video src={require('http://localhost:3000/path/to/file.mp4')} controls />

but still errors:

Module not found: Error: Cannot resolve module 'http://localhost:3000/path/to/file.mp4' in path/to/file.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'
}

but no luck


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)


I also noticed in the webpack documentation under loader conventions that file-loader will load video files. webpack documentation image 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.


Resources

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I had the same problem, my solution is:

It uses https://github.com/webpack/html-loader and https://github.com/webpack/url-loader:

The loaders configuration:

  loaders: [{
      test: /.html$/,
      loader: 'html-loader?attrs[]=video:src'
    }, {
      test: /.mp4$/,
      loader: 'url?limit=10000&mimetype=video/mp4'
  }]

And in html:

A simple video tag, remeber webpack uses path referenced to the html file.

<video src="../../../assets/videos/cover1.mp4"></video>

This works for me.

References: https://github.com/webpack/html-loader/issues/28


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...