>  기사  >  웹 프론트엔드  >  Vue-cli를 여러 페이지를 지원하는 기록 모드로 변환하는 방법

Vue-cli를 여러 페이지를 지원하는 기록 모드로 변환하는 방법

小云云
小云云원래의
2018-01-16 11:10:011768검색

이 글은 주로 Vue-cli를 여러 페이지를 지원하는 히스토리 모드로 변환하는 방법을 자세히 소개합니다. 관심 있는 친구들이 참고할 수 있기를 바랍니다.

제목은 정확하지 않을 수 있지만 아마도 요구 사항일 것입니다.

Vue-cli를 사용하여 다중 항목, 다중 페이지 사이트를 구축하십시오. 즉, html-webpack을 통해 여러 .html 파일이 생성됩니다. -plugin 플러그인. 기본적으로 아래에서는 index.html 항목만 http://www.xxx.com/xxx/xxx와 같은 기록 모드를 사용할 수 있고 다른 항목은 다음과 같은 해시 모드만 사용할 수 있습니다. http://www.xxx.com/admin.html#/xxx/xxx, webpack-dev-middleware가 모든 경로를 index.html 파일로 지정하기 때문에 기록 모드가 필요합니다. 문제가 있습니다.

정말 너무 많습니다. 둘째, 방금 기사 작성을 마쳤는데 connect-history-api-fallback 플러그인이 이 작업을 수행한다는 것을 발견했습니다...

메서드가 다음과 같이 업데이트되었습니다.

빌드를 수정합니다. /dev-server.js 파일


app.use(require('connect-history-api-fallback')())

Change Be


var history = require('connect-history-api-fallback')
app.use(history({
  rewrites: [
    { from: 'index', to: '/index.html'}, // 默认入口
    { from: /\/backend/, to: '/backend.html'}, // 其他入口
    { from: /^\/backend\/.*$/, to: '/backend.html'},
  ]
}))

자세한 규칙을 참조하세요: https://github.com/bripkens/connect-history-api-fallback

--- ----------- 다음 코드는 무시하세요. --------------

이제 모든 항목이 기록 모드를 지원하도록 몇 가지 변경해 보겠습니다.

1. , 빌드 디렉터리 파일에 setup-dev-server.js를 생성합니다. 내부 코드는 다음과 같습니다.


const path = require('path')
const webpack = require('webpack')
const clientConfig = require('./webpack.dev.conf') // 引入开发环境下的 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)
  // 关键代码开始
  // 因为开发环境下, 所有的文件都在内存里, 包括由 html-webpack-plugin 生成的 .html 文件, 所以我们需要用 webpack-dev-middleware 提供的 api 从内存里读取
  clientCompiler.plugin('done', () => {
    const fs = devMiddleware.fileSystem // 访问内存
    const filePath = path.join(clientConfig.output.path, 'index.html') // 读取的文件, 文件名和 html-webpack-plugin 生成的文件名要求一致
    if (fs.existsSync(filePath)) { // 判断下文件是否存在
      const index = fs.readFileSync(filePath, 'utf-8') // 从内存里取出
      opts.indexUpdated(index) // 将取出的文件通过 indexUpdated 函数返回, 这个函数怎么来的, 后面会说明
    }
    const adminPath = path.join(clientConfig.output.path, 'backend.html') // 同上, 这是第二个入口生成的 .html 文件, 如果还有其他入口, 这个多复制几份
    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)
  // 当修改 html-webpack-plugin 模版时, 自动刷新整个页面
  clientCompiler.plugin('compilation', function(compilation) {
    compilation.plugin('html-webpack-plugin-after-emit', function(data, cb) {
      hotMiddleware.publish({
        action: 'reload'
      })
      cb()
    })
  })
}

2. build/dev-server.js 파일을 수정합니다

주로 var에서 파일을 수정합니다. app = express() to module.exports = app.listen(port, function (err) {


var app = express()

var indexHTML
var adminHTML

// 引用前面创建的文件, 并将两个保存内容的函数传过去, 这里保存内容的变量写成对象或者数组也可以, 还可以少点代码
require('../config/setup-dev-server')(app, {
  indexUpdated: index => {
    indexHTML = index
  },
  adminUpdated: index => {
    adminHTML = index
  },
})

// 加载反向代理
Object.keys(proxyTable).forEach(function(context) {
  var options = proxyTable[context]
  if (typeof options === 'string') {
    options = {
      target: options
    }
  }
  app.use(proxyMiddleware(context, options))
})
// 设置静态文件夹路由
var staticPath = path.posix.join(config.assetsPublicPath, config.assetsSubDirectory)
app.use(staticPath, express.static('./static'))

// 入口1路由
app.get(['/', '/category/:id'], (req, res) => {
  res.send(indexHTML)
})

// 入口2路由
app.get(['/backend', '/backend/*'], (req, res) => {
  res.send(adminHTML)
})

// 404 页面
app.get('*', (req, res) => {
  res.send('HTTP STATUS: 404')
})

app.use(function(req, res, next) {
  var err = new Error('Not Found')
  err.status = 404
  next(err)
})

app.use(function(err, req, res) {
  res.status(err.status || 500)
  res.send(err.message)
})

module.exports = app.listen(port, function(err) {

3.npm 사이의 코드 dev를 실행하고 행복하게 코드 작성을 시작하세요

관련 권장 사항:

HTML5 기록 모드란 무엇입니까

HTML5의 기록 모드에 대한 자세한 설명

기록의 여러 방법

위 내용은 Vue-cli를 여러 페이지를 지원하는 기록 모드로 변환하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.