javascript Webpack:导出到窗口中的现有模块
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30539725/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Webpack: export to existing module in window
提问by rodrigo-silveira
My goal is to use Webpack to export an isolated component into an assumed global object.
我的目标是使用 Webpack 将一个孤立的组件导出到一个假定的全局对象中。
index.html
索引.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
.
在上面的示例中,我假设有一个全局对象/模块,它具有一个属性something
,该属性将附加其他模块。所以我想将我的隔离模块附加到全局MyApp.something
对象而不破坏MyApp
或MyApp.something
.
webpack.config.js
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
源代码/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...
我已经尝试将 Webpack 设置output.libraryTarget
为每个可能的值(参见http://webpack.github.io/docs/configuration.html#output-librarytarget),以及使用的值,output.library
以便它包含直接命名空间与我的模块。没有什么能如我所愿...
回答by Matt Derrick
output.library
can be an array like below:
output.library
可以是如下数组:
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.
这将在窗口上创建一个对象,window.MyApp.something
或者,window.MyApp
如果它已经存在,则将其添加到。