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...
MyApp.something
if it already exists? You could addMyApp
as anexternal
and set the value on it yourself. – Jamshedpur