Webpack: export to existing module in window
Asked Answered
S

1

23

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...

Symbolics answered 29/5, 2015 at 21:58 Comment(1)
You're wanting to merge your package with MyApp.something if it already exists? You could add MyApp as an external and set the value on it yourself.Jamshedpur
F
42

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.

Foushee answered 25/9, 2015 at 15:58 Comment(3)
Thanks, this was what I needed to answer my own questionMapping
What if I want it to write all the exports to MyApp, instead of putting all exports on a something subobject? If I try library: ['MyApp'], then it does not create MyApp if it doesn't exist. Why is this so hard in Webpack? So easy in Rollup.Copycat
what if each library has a config? I guess you can pass an object library: [ { name: 'MyApp' }, { name: 'something' }] ?Copestone

© 2022 - 2024 — McMap. All rights reserved.