webpack external react 时只能使用其全局变量或相对路径怎么办?


我想把react作为external lib 从bundle里面分离出来,但是require好像不起作用呢,在配置里起得名字也不好使。只能使用文件的相对路径来require或者干脆不require就行了。可是我想使用cmd模式用require来把它引入怎么办?


 //配置如下
var webpack = require('webpack');
var path = require('path');
var config = {
    entry: [
        path.resolve(__dirname, 'scripts/main.js')
    ],
    output: {
        path: path.resolve(__dirname, 'build'),
        libraryTarget: "umd",
        library: '',
        filename: 'bundle.js'
    },
    externals: [
        //第一种写法
        {"../build/react.min.js": 'React'}
        //第二种写法,这货怎么用的有木有大神教一下- -!
        {"../build/react.min.js": {
            root: 'ReactJS',
            commonjs: ["./ReactJS", "ReactJS"],
        }}

    ],

    module: {
        loaders: [{
            exclude: "scripts/react.min.js",
            test: /\.js$/,
            loaders: ['babel']
        }]
    }
};


 //js如下
'use strict';
//第一种配置,下面这句话写不写都不会报错。
var React = require('../build/react.min.js');
console.log('main' + 1 + 2);
var Main = React.createClass({
    getInitialState: function() {
        return {
            switch: true
        };
    },
    _toggle() {
        this.setState({
            switch: !this.state.switch
        });
    },
    render() {
        return (


<div>
                <input type="button" onClick={this._toggle} value="Press Me!"/>

            </div>


        );
    }
});
React.render(<Main />, document.body);

reactjs webpack JavaScript

变研的熊猫 10 years, 8 months ago

我是这样写的


 javascript


 //webpack.config.js
module.exports = {
    externals: {
      'react': 'window.React'
    },
    //...
}

//main.js
var React = require('react');

//home.html
<script src='../build/react.min.js' type="text/javascript"></script>

Water answered 10 years, 8 months ago

Your Answer