標(biāo)題可能描述不準(zhǔn)確, 大概就是這么個需求:
用 Vue-cli 搭建一個多入口, 多頁面的站點, 也就是通過html-webpack-plugin插件會生成多個 .html 文件, 在默認(rèn)下, 是只有 index.html 這個入口可以用 history 模式, 如: http://www.xxx.com/xxx/xxx, 而其他的入口只能用 hash 模式, 如: http://www.xxx.com/admin.html#/xxx/xxx, 因為webpack-dev-middleware會將所有的路由都指向 index.html 文件, 假如線上的時候, 都需要 history 模式, 這樣多少會造成麻煩.
真是太二了, 剛寫完文章就發(fā)現(xiàn)connect-history-api-fallback這個插件就是做這個的...
方法更新如下:
修改 build/dev-server.js 文件
app.use(require('connect-history-api-fallback')())改成
var history = require('connect-history-api-fallback')app.use(history({ rewrites: [ { from: 'index', to: '/index.html'}, // 默認(rèn)入口 { from: ///backend/, to: '/backend.html'}, // 其他入口 { from: /^//backend//.*$/, to: '/backend.html'}, ]}))具體規(guī)則就參考: https://github.com/bripkens/connect-history-api-fallback
-------------- 以下代碼請無視 --------------
下面我們就來改造下, 讓所有入口都支持 history 模式:
1. 首先, 我們在 build 目錄下建立個 setup-dev-server.js 文件, 里面代碼如下:
const path = require('path')const webpack = require('webpack')const clientConfig = require('./webpack.dev.conf') // 引入開發(fā)環(huán)境下的 webpack 配置文件module.exports = function setupDevServer(app, opts) { const clientCompiler = webpack(clientConfig) // 加載 webpack-dev-middleware 插件 const devMiddleware = require('webpack-dev-middleware')(clientCompiler, { publicPath: clientConfig.output.publicPath, stats: { colors: true, chunks: false } }) app.use(devMiddleware) // 關(guān)鍵代碼開始 // 因為開發(fā)環(huán)境下, 所有的文件都在內(nèi)存里, 包括由 html-webpack-plugin 生成的 .html 文件, 所以我們需要用 webpack-dev-middleware 提供的 api 從內(nèi)存里讀取 clientCompiler.plugin('done', () => { const fs = devMiddleware.fileSystem // 訪問內(nèi)存 const filePath = path.join(clientConfig.output.path, 'index.html') // 讀取的文件, 文件名和 html-webpack-plugin 生成的文件名要求一致 if (fs.existsSync(filePath)) { // 判斷下文件是否存在 const index = fs.readFileSync(filePath, 'utf-8') // 從內(nèi)存里取出 opts.indexUpdated(index) // 將取出的文件通過 indexUpdated 函數(shù)返回, 這個函數(shù)怎么來的, 后面會說明 } const adminPath = path.join(clientConfig.output.path, 'backend.html') // 同上, 這是第二個入口生成的 .html 文件, 如果還有其他入口, 這個多復(fù)制幾份 if (fs.existsSync(adminPath)) { const admin = fs.readFileSync(adminPath, 'utf-8') opts.adminUpdated(admin) } }) // 加載熱重載模塊 app.use(require('webpack-hot-middleware')(clientCompiler)) var hotMiddleware = require('webpack-hot-middleware')(clientCompiler) // 當(dāng)修改 html-webpack-plugin 模版時, 自動刷新整個頁面 clientCompiler.plugin('compilation', function(compilation) { compilation.plugin('html-webpack-plugin-after-emit', function(data, cb) { hotMiddleware.publish({ action: 'reload' }) cb() }) })}
新聞熱點
疑難解答
圖片精選