如何从外部访问webpack bundle(js)中的mobx对象

时间:2016-09-19 12:53:29

标签: javascript reactjs webpack mobx mobx-react

我想访问在JSX文件中声明的对象(即MOBX对象)。我使用webpack将所有jsx文件捆绑在一个输出文件(bundle.js)中。但是我想访问bundle文件中的一些函数和对象。我们怎么做到这一点?

我的webconfig.config.js

var webpack = require('webpack');
var path = require('path');

var buildDir = path.resolve(__dirname, './wwwroot/scripts');
var scriptsDir = path.resolve(__dirname, './Scripts');

var config = {
    entry: {
        main: scriptsDir + '/app'
    },
    output: {
        path: buildDir,
        filename: 'bundle.js',
        libraryTarget: 'var',
        library: 'MyLibrary'
    },
    externals: {
    },
    debug: true,
    // Important! Do not remove ''. If you do, imports without
    // an extension won't work anymore!
    resolve: {
        extensions: ['', '.js', '.jsx']
    },
    module: {
        loaders: [
          {
              test: /\.jsx?$/,
              // Enable caching for improved performance during development
              // It uses default OS directory by default. If you need
              // something more custom, pass a path to it.
              // I.e., babel?cacheDirectory=<path>
              loaders: ['babel?cacheDirectory'],
              exclude: /(node_modules)/
          }
        ]
    }
};

module.exports = config;

JSX文件

var React = require('react');
var ReactDOM = require('react-dom');
var mobx = require('mobx');
var mobxReact = require('mobx-react');
var mobxDevtools = require('mobx-react-devtools');

mobx.useStrict(true);

var todoFactory = function (title) {
    var todo = {
        id: Math.random(),
        toggleStatus: mobx.action(function toggleStatus() {
            todo.finished = !todo.finished;
        })
    };
    mobx.extendObservable(todo,
        {
            title: title,
            finished: false
        }
    );
    return todo;
};

var todoListFactory = function () {
    var todoList = {
        addTodo: mobx.action(function addTodo(todo) {
            todoList.todos.push(todo);
        }),
        addTodos: mobx.action(function addTodos(todos) {
            todoList.todos = todoList.todos.concat(todos);
        })
    };

    mobx.extendObservable(todoList, {
        todos: [],
        unfinishedTodoCount: function () {
            return todoList.todos.filter(function (todo) {
                return !todo.finished;
            }).length;
        }
    });

    return todoList;
};

var TodoListView = mobxReact.observer(function TodoListView() {
    var devtools = mobxDevtools ? React.createElement(mobxDevtools.default) : null;

    var listItems = this.props.todoList.todos.map(function (todo) {
        return React.createElement(TodoView, { todo: todo, key: todo.id });
    });

    return React.createElement('div', null,
        devtools,
        React.createElement('ul', null, listItems),
        'Tasks left: ' + this.props.todoList.unfinishedTodoCount
    );
}
);

var TodoView = mobxReact.observer(
    React.createClass({
        displayName: 'TodoView',
        render: function () {
            var todo = this.props.todo;
            return React.createElement('li', null,
                React.createElement('input', {
                    type: 'checkbox',
                    checked: todo.finished,
                    onClick: this.selectHandler
                }),
                todo.title
            );
        },
        selectHandler: function () {
            this.props.todo.toggleStatus();
        }
    })
);

var store = todoListFactory();

store.addTodos([todoFactory('Get Coffee'), todoFactory('Write simpler code')]);
store.todos[0].toggleStatus(true);

var Practice = React.createClass({
    render: function () {
        return (
            <div>
                <TodoListView todoList={store} />
            </div>
        );
    }
});

module.exports = Practice;

我的目标是能够从外部访问商店对象。像'MyLibrary.store'之类的东西。怎么可能这样呢?

谢谢, 马文

1 个答案:

答案 0 :(得分:1)

1)如果未在入口点文件中定义商店对象,则应在入口点导入和导出商店对象。

// entry_point.js

...
var store = require('./file_with_store').store;
exports.store = store;

之后,由于您已将library: 'MyLibrary'属性添加到webpack配置中,因此您可以访问 MyLibrary.store

2)如果商店对象已经在入口点文件中,那么只需添加:

exports.store = store;