我正在使用Webpack开发多个页面的Web应用程序。在开发环境中,我希望Webpack服务器根据文件路径打开url中不同目录下的index.html文件,例如:http://localhost/index/file/to/the/directories/,然后index.html文件自动提供,无需输入index.html在网址中。使用插件的Webpack服务器:webpack-dev-middleware,webpack-hot-middleware。有没有办法实现这个使命?
项目目录如下:
-build -dev-server.js -webpack.conf.js -src -directoryA -mainA.js -directoryB -mainB.js -template -mainA.html -mainB.html
项目中使用的Vue.js,简化了以下代码。
webpack.conf.js:
var webpack = require('webpack')
var HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
entry: {
mainA: './src/directoryA/mainA.js',
mainB: './src/directoryB/mainB.js',
},
output: {
path: './src'
filename: '[name].js',
publicPath: '/'
},
plugins: [
new HtmlWebpackPlugin({
filename: 'directoryA/index.html',
template: 'template/mainA.html',
inject: true,
chunks: ['mainA'],
}),
new HtmlWebpackPlugin({
filename: 'directoryB/index.html',
template: 'template/mainB.html',
inject: true,
chunks: ['mainB'],
}),
],
}
dev-server.js如下:
var path = require('path')
var express = require('express')
var webpack = require('webpack')
var webpackConfig = require('./webpack.conf')
var port = process.env.PORT || config.dev.port
var app = express()
var compiler = webpack(webpackConfig)
var devMiddleware = require('webpack-dev-middleware')(compiler, {
publicPath: webpackConfig.output.publicPath,
quiet: true
})
var hotMiddleware = require('webpack-hot-middleware')(compiler, {
log: () => {}
})
// force page reload when html-webpack-plugin template changes
compiler.plugin('compilation', function (compilation) {
compilation.plugin('html-webpack-plugin-after-emit', function (data, cb) {
hotMiddleware.publish({ action: 'reload' })
cb()
})
})
// serve webpack bundle output
app.use(devMiddleware)
app.use(hotMiddleware)
var uri = 'http://localhost:' + port
var _resolve
var readyPromise = new Promise(resolve => {
_resolve = resolve
})
console.log('> Starting dev server...')
devMiddleware.waitUntilValid(() => {
console.log('> Listening at ' + uri + '\n')
// when env is testing, don't need open it
if (autoOpenBrowser && process.env.NODE_ENV !== 'testing') {
opn(uri)
}
_resolve()
})
var server = app.listen(port)
module.exports = {
ready: readyPromise,
close: () => {
server.close()
}
}
现在,我启动服务器,在浏览器中打开网址:http://localhost:3000/directoryA/。我希望它会打开目录下的index.html文件,但它不是。我怎么能让它发挥作用?