Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
209 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...