从脚本标记的全局范围调用webpack模块中的函数
Invoke function in webpack module from global scope in script tag
我似乎无法理解这个问题:
想象一个简单的示例应用程序,它带有一个javascript模块app1.js
,在最简单的版本中看起来是这样的:
function configure() {
// configure app
}
function start(id) {
// start app
}
// This is what I dislike and would like to find a better solution!
window.APP = {start: start};
export default {configure};
我有一个html页面app.html
,看起来像这样:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div id="view"></div>
<script src="app.bundle.js"></script>
<script>APP.start('view');</script>
</body>
</html>
和一个看起来像这样的webpack配置文件webpack.config.js
:
const webpack=require('webpack');const-path=require('path');
module.exports = {
entry: {'app': './app.js'},
output: {
path: __dirname,
filename: '[name].bundle.js'
},
module: {
loaders: [{
test: /'.js$/,
exclude: /node_modules/,
loader: 'babel?presets=es2015'
}]
}
};
我能想到的唯一方法是将start
函数导出到窗口对象(window.APP = {start: start}
)中的APP名称空间,就像在模块之前一样。有没有更好的(更模块化的方式)来做到这一点?
您真的需要从外部"触发"或"启动"脚本吗?考虑到您上面描述的模式,您可以让您的webpack入口点启动(例如,它导入相关模块,然后使用它们)。
如果你真的需要将你的webpack构建加载为某种库,供页面上的其他js使用,你需要查看webpack配置中的output.library和output.libraryTarget
选项。它们告诉webpack将您的捆绑包构建为库,libraryTarget
指定在运行时如何定义库(例如,var
选项将您的库定义为一个变量,它可能是一个全局变量,类似于jQuery
)。
相关文章:
- 如何在Webpack中从导出中排除供应商模块peerDependencies
- 通过Webpack导入模块中的图像
- Webpack通过npm将代码拆分为单独的模块,以及如何编译es6
- 无法使用Webpack加载ES6模块
- 可以'I don’我不明白;使用webpack和es6模块进行EventEmitter
- 为具有核心模块和子模块的应用程序构建Webpack
- Javascript:Webpack+Typescript+Namespace(内部模块)
- 如何使用 webpack 要求或仅从模块导入必要的导出
- 从脚本标记的全局范围调用webpack模块中的函数
- 如何从浏览器开发工具访问 Webpack 模块
- Webpack 模块构建失败意外令牌(rails react build)
- 在基于require.js的项目中加载webpack模块返回null
- Webpack模块未找到:错误:无法解析模块
- 如何将变量传递给WebPack模块
- 获取webpack模块的压缩大小
- Webpack模块类型的源映射指向'undefined'文件
- Webpack模块依赖,就像在requirerequirements中一样
- Webpack模块css依赖项
- 使用webpack模块
- React的Webpack模块分析错误