Created
March 14, 2017 15:05
-
-
Save knjname/4c0b063a4ec35f7f4fa9cb164c79f5b5 to your computer and use it in GitHub Desktop.
Webpack with memory-fs running on an express server.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const webpack = require("webpack"); | |
const express = require("express"); | |
const MemoryFileSystem = require("memory-fs") | |
// 仮想的にファイルを用意する (cf. https://github.com/webpack/memory-fs) | |
const fs = new MemoryFileSystem() | |
fs.writeFileSync("/index.html", | |
`<h1>My App!</h1><script src="bundle/app.js"></script>`) | |
fs.mkdirpSync("/src") | |
fs.writeFileSync("/src/index.js", | |
`import "./dep.js"; console.log("index.js!");`); | |
fs.writeFileSync("/src/dep.js", | |
`console.log("dep.js!");`); | |
// Webpackの準備 | |
const compiler = webpack({ | |
entry: "/src/index.js", | |
output: { | |
path: "/bundle/", | |
filename: "app.js", | |
}, | |
}) | |
// memory-fs で Webpack を動かすためのおまじない | |
// https://github.com/webpack/webpack/issues/1562 | |
compiler.inputFileSystem = fs | |
compiler.outputFileSystem = fs | |
compiler.resolvers.normal.fileSystem = fs | |
compiler.resolvers.context.fileSystem = fs | |
// サーバの立ち上げ | |
const devserver = express(); | |
devserver.get("/", (req, res) => { | |
res.setHeader("Content-Type", "text/html") | |
res.send(fs.readFileSync("/index.html")); | |
}); | |
devserver.get("/bundle/app.js", (req, res) => { | |
compiler.run((err, stats) => { | |
if (err) { | |
res.send(err); | |
return | |
} | |
res.send(fs.readFileSync("/bundle/app.js")); | |
}); | |
}); | |
devserver.get("/*", (req, res) => { | |
res.send(fs.readFileSync(req.path)); | |
}); | |
devserver.listen(13000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment