使用webpack在react组件中实现jwplayer的正确方法(react-starter-kit)

Ani*_*pta 6 jwplayer reactjs jwplayer6 webpack es6-module-loader

我正在使用jwpalyer制作VideoPlayer反应组件,我正在使用webpack es6来加载模块webpack支持npm模块加载并且jwplayer没有npm

所以我试图使用es6 import包含jwplayer.js,但它给了我错误ReferenceError:window未定义

所以任何人都可以帮我正确设置webpack的jwplayer

  import React, { PropTypes, Component } from 'react';
  import $ from 'jquery';
  import Player from "./lib/jwplayer/jwplayer.js";
  import styles from './VideoPayer.css';
  import withStyles from '../../decorators/withStyles';
  import Link from '../Link';

  @withStyles(styles)
  class VideoPlayer extends Component {

    static propTypes = {
      className: PropTypes.string,
    };

    static defaultProps = {
      file: '',
      image: ''
    };

    constructor(props) {
      super(props);
      this.playerElement = document.getElementById('my-player');
    }


    componentDidMount() {
      if(this.props.file) {
        this.setupPlayer();
      }
    }

    componentDidUpdate() {
      if(this.props.file) {
        this.setupPlayer();
      }
    }

    componentWillUnmount() {
       Player().remove(this.playerElement);
    }

    setupPlayer() {
      if(Player(this.playerElement)) {
        Player(this.playerElement).remove();
      }

      Player(this.playerElement).setup({
        flashplayer: require('./lib/player/jwplayer.flash.swf'),
        file: this.props.file,
        image: this.props.image,
        width: '100%',
        height: '100%',
      });
    }

    render() {
      return (
        <div>
          <div id="my-player" className="video-player"></div>
        </div>
      )
    }
  }

export default VideoPlayer;
Run Code Online (Sandbox Code Playgroud)

Ngz*_*Ngz 6

我想这就是你需要做的:

  1. 将窗口定义为bundle的外部窗口,以便不破坏其他库中对它的引用.
  2. 公开全局变量,jwplayer以便附加密钥
  3. (可选)为jwplayer库创建别名

我已经测试了它,这个配置适用于我,但只适用于客户端,而不是服务器上或同构/普遍的.

webpack.config.js:

// Declare window as external
externals: {
    'window': 'Window'
},
// Create an easy binding so we can just import or require 'jwplayer'
resolve: {
    alias: {
        'jwplayer':'../path/to/jwplayer.js'
    }
},
// Expose jwplayer as a global variable so we can attach the key, etc.
module: {
    loaders: [
        { test: /jwplayer.js$/, loader: 'expose?jwplayer' }
    ]
}
Run Code Online (Sandbox Code Playgroud)

然后你可以import jwplayer from 'jwplayer'require('jwplayer').

  • 有没有人有一个使用jwplayer与webpack的回购示例? (3认同)