-->

Webpack: export to existing module in window

2019-01-18 11:33发布

问题:

My goal is to use Webpack to export an isolated component into an assumed global object.

index.html

<script>
   var MyApp = window.MyApp || {};
   MyApp.something = MyApp.something || {};
</script>
<script src="my-isolated-module.js"></script>

//
// other modules/components loaded here...
//

<script>
   MyApp.something.myIsolatedModule.run();
</script>

In the above example, I assume there's a global object/module that has a property something that will have other modules attached to it. So I want to attach my isolated module to the global MyApp.something object without destroying either MyApp or MyApp.something.

webpack.config.js

var webpack = require('webpack');
var UglifyJsPlugin = require('webpack/lib/optimize/UglifyJsPlugin');

module.exports = {
    target: 'web',
    context: __dirname + '/src/',
    entry: './main.jsx',
    output: {
        path: __dirname + '/dist/',
        filename: 'app.bundle.js',
        library: 'something',
        libraryTarget: 'var'
    },
    resolve: {
        extensions: ['', '.js', '.jsx']
    },
    module: {
        loaders: [
            {test: /\.jsx$/, loader: '../node_modules/jsx-loader'}
        ]
    },
    externals: {
        react: {
            root: 'React',
            commonjs: 'react',
            commonjs2: 'react',
            amd: 'react'
        }
    },

    plugins: [
        new UglifyJsPlugin()
    ]
};

src/main.jsx

module.exports = {
    myIsolatedModule: require('./MyIsolatedModule')
};

I've tried setting Webpack's output.libraryTarget to every possible value (see http://webpack.github.io/docs/configuration.html#output-librarytarget), as well as playing around with the value of output.library so that it would include the direct namespace withing my module. Nothing works as I would like...

回答1:

output.library can be an array like below:

output: {
    library: ['MyApp', 'something']
}

This will either create an object on the window window.MyApp.something or, will add it to window.MyApp if it already exists.