从脚本标记的全局范围调用webpack模块中的函数

Invoke function in webpack module from global scope in script tag

本文关键字:webpack 模块 函数 调用 全局 脚本 范围      更新时间:2023-09-26

我似乎无法理解这个问题:

想象一个简单的示例应用程序,它带有一个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)。