如何将变量传递给 WebPack 模块?

How to pass variable to WebPack module?

我正在尝试了解如何使用 WebPack 将我所有模块特定的 JS 源捆绑到一个文件中。对于这个示例,我只使用了一个 JS 文件。

通常我会这样写我的JavaScript和HTML:

foo.js

var foo = function (className) {
  this.className = null;

  this.init(className)
}

foo.prototype = {
  "init": function (className) {
    this.className = className
  },

  "render": function () {
    var o = document.createElement("span")

    o.setAttribute("class", this.className)
    o.textContent = "foo's className is " + this.className

    return o
  }
}

index.html

<html>
<head>
    ...
    <script src="foo.js"></script>
</head>
<body>
    ...
    <div id="foobar"></div>
    <script>
        ;(function () {
            var className = "bar"
            var o = new foo(className)

            document.getElementById("foobar").appendChild(o.render())
        })()
    </script>
    ...
</body>
</html>

大多数情况下,脚本部分由 PHP 应用程序注入,变量的值将来自某些后端代码。

现在我正在尝试将我的 JS 代码与 WebPack 捆绑在一起。 webpack.config.js 看起来像这样:

module.exports = {
  context: __dirname,
  entry: {
    bundle: [
      "./src/foo.js"
    ]
  },

  output: {
    filename: "dst/[name].js"
  }
}

我更新 foo.js 文件:

...
module.exports = foo

现在我用 webpack -p 编译包,然后我更改 HTML 以包含新的 bundle.js 并要求 foo.

index.html

<html>
<head>
    ...
    <script src="dst/bundle.js"></script>
</head>
<body>
    ...
    <div id="foobar"></div>
    <script>
        ;(function () {
            var foo = require("foo")
            var className = "bar"
            var o = new foo(className)

            document.getElementById("foobar").appendChild(o.render())
        })()
    </script>
    ...
</body>
</html>

但现在我只得到以下错误:

ReferenceError: requrie is not defined
    var foo = requrie("foo")

如何使此代码与 WebPack 一起工作? WebPack 是执行此操作的正确工具吗?

我终于找到了解决办法。像这样更新 webpack.config.js

module.exports = {
  context: __dirname,
  entry: {
      "./src/foo.js"
    ]
  },

  output: {
    library: "foo",
    libraryTarget: "umd",
    filename: "dst/[name].js"
  }
}