Webpack:导出到窗口中的现有模块 [英] Webpack: export to existing module in window
问题描述
我的目标是使用 Webpack 将一个孤立的组件导出到一个假定的全局对象中.
My goal is to use Webpack to export an isolated component into an assumed global object.
<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>
在上面的例子中,我假设有一个全局对象/模块,它有一个属性 something
将有其他模块附加到它.所以我想将我的隔离模块附加到全局 MyApp.something
对象而不破坏 MyApp
或 MyApp.something
.
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
.
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')
};
我尝试将 Webpack 的 output.libraryTarget
设置为每个可能的值(请参阅 http://webpack.github.io/docs/configuration.html#output-librarytarget),以及使用 output.library
的值以便它将直接命名空间包含在我的模块中.没有什么能如我所愿...
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...
推荐答案
output.library
可以是如下数组:
output: {
library: ['MyApp', 'something']
}
这将在窗口 window.MyApp.something
上创建一个对象,或者将它添加到 window.MyApp
(如果它已经存在).
This will either create an object on the window window.MyApp.something
or, will add it to window.MyApp
if it already exists.
这篇关于Webpack:导出到窗口中的现有模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!