使用 Node.js 進行簡單的 webpack 設定

資料夾結構

.
├── lib
├── modules
|   ├── misc.js
|   ├── someFunctions.js
├── app.js
├── index.html
├── package.json
├── webpack.config.js
└── webserver.js   

package.json

{
  "name": "webpack-example-with-nodejs",
  "version": "1.0.0",
  "description": "Example using webpack code-splitting with some Node.js to support the example",
  "main": "webserver.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "@Gun",
  "license": "ISC",
  "devDependencies": {
    "body-parser": "^1.17.1",
    "express": "^4.15.2",
    "http": "0.0.0",
    "morgan": "^1.8.1",
    "multer": "^1.3.0",
    "webpack": "^2.4.1"
  }
}

webpack.config.js

var path = require('path'); // used to get context

module.exports = {
    context: path.join(__dirname, 'app'), // resolves entry below, must be absolute path
    entry: './app.js', // entry point or loader for the application
    output: {
        path: path.join(__dirname, 'app/lib'), // express static folder is at /app/lib
        filename: '[name].bundle.js', // the file name of the bundle to create.  [name] is replaced by the name of the chunk (code-splitting)
        publicPath: 'static' // example uses express as the webserver
    }
};

webserver.js

var express = require('express'),
    path = require('path'),
    bodyParser = require('body-parser'),
    multer = require('multer')()
    logger = require('morgan'),
    fs = require('fs'),
    http = require('http');

var app = express();
var port = 31416;

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(logger('short'));
app.use('/jsBundles',express.static('lib'));
app.get('/', function(request, response){
    response.sendFile(__dirname + '/index.html');
});

var server = http.createServer(app).listen(port, function(){
    console.log("I feel a disturbance in the port:" + port);
});

index.html

<!DOCTYPE html>
<html>
    <body>
        <div id="someValue"><label for="num">Enter a number:</label><input id="num" /></div>
        <div class="buttonList">
            <ul>
                <li><button id="doubleIt">double it</button></li>
                <li><button id="tripleIt">triple it</button></li>
            </ul>
        </div>
        <div id="someOtherValue">
            And the count shall be: <span id="theCount"></span>
        </div>
        <script src="/jsBundles/main.bundle.js"></script>        
    </body>
</html>

app.js

require(['./modules/someFunctions'],function(){
        window.onload = function(){
                var someFunctions  = require('./modules/someFunctions');             
                document.getElementById('doubleIt').onclick = function(){
                        var num = document.getElementById('num').value;
                        document.getElementById('theCount').innerHTML = someFunctions.Double(num);
                };

                document.getElementById('tripleIt').onclick = function(){
                        var num = document.getElementById('num').value;
                        document.getElementById('theCount').innerHTML = someFunctions.Triple(num);
                };
        };
});

misc.js

var self = {};
self.isNumber = function(value){
    // http://stackoverflow.com/questions/9716468/is-there-any-function-like-isnumeric-in-javascript-to-validate-numbers
    return !isNaN(parseFloat(value)) && isFinite(value);
};
module.exports = self;

someFunctions.js

require(['./misc'], function(){
    var misc= require('./misc');

    var self = {};
    self.Double = function(value){
        if(!misc.isNumber(value)){
            return 0;
        };
        return value*2;
    }

    self.Triple = function(value){
        if(!misc.isNumber(value)){
            return 0;
        };
        return value*3;
    }

    module.exports = self;
});

注意

執行 npm i –save-dev 來安裝依賴項

安裝依賴項後執行節點。\ node_modules \ webpack \ bin \ webpack.js

執行節點 webserver.js 以啟動伺服器