【问题标题】:How to pass variable to WebPack module?如何将变量传递给 WebPack 模块?
【发布时间】:2015-10-10 18:21:54
【问题描述】:

我试图了解,如何使用 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 甚至是执行此操作的正确工具吗?

【问题讨论】:

    标签: javascript php webpack


    【解决方案1】:

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

    module.exports = {
      context: __dirname,
      entry: {
          "./src/foo.js"
        ]
      },
    
      output: {
        library: "foo",
        libraryTarget: "umd",
        filename: "dst/[name].js"
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-08-10
      • 1970-01-01
      • 2014-09-18
      • 1970-01-01
      • 2018-09-07
      • 1970-01-01
      • 1970-01-01
      • 2019-12-10
      • 2023-03-23
      相关资源
      最近更新 更多