2015-10-10 42 views
0

我想了解,如何使用WebPack將我所有模塊特定的JS源代碼捆綁到一個文件中。對於這個示例,我只使用一個JS文件。如何將變量傳遞給WebPack模塊?

通常我會寫我的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甚至是做這件事的正確工具嗎?

回答

0

我終於找到了解決方案。更新webpack.config.js像這樣:

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

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