Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

javascript - Webpack: export to existing module in window

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...