1

我正在使用 Webpack 开发一个包含多个页面的 Web 应用程序。在开发环境中,我希望 Webpack 服务器根据文件路径打开 url 中不同目录下的 index.html 文件,例如:http://localhost/index/file/to/the/directories/,然后是 index .html 文件自动提供,无需在 url 中输入 index.html。使用插件的 Webpack 服务器:webpack-dev-middleware、webpack-hot-middleware。有没有办法实现这个使命?

项目目录如下:

    -建造
      -dev-server.js
      -webpack.conf.js
    -src
      -目录A
        -mainA.js
      -目录B
        -mainB.js
    -模板
      -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 文件,但事实并非如此。我怎样才能让它工作?

4

0 回答 0