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

How to access mobx object in webpack bundle(js) from external

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

我的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) 如果入口点文件中未定义商店对象,则应在入口点中导入和导出商店对象。

// entry_point.js

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

之后,由于你在webpack配置中添加了library: 'MyLibrary' 属性,你可以访问MyLibrary.store

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

exports.store = store;