Bootstrap

前端如何在本地启动一个服务,跑打包后的项目

首先在package.json文件中加入如下代码:

"build:self": "cross-env NODE_ENV=development env_config=test ASSET_PATH=/ node build/build.js",
"preview": "node build/index.js --preview"

然后安装如下插件

npm i connect
npm i runjs
npm i serve-static

然后在bulid文件夹下创建一个index.js的文件
在这里插入图片描述
文件代码如下:

const { run } = require('runjs')
const chalk = require('chalk')
const rawArgv = process.argv.slice(2)
const args = rawArgv.join(' ')

if (process.env.npm_config_preview || rawArgv.includes('--preview')) {
  const report = rawArgv.includes('--report')

  run(`npm run build:self ${args}`)

  const port = 9526
  const publicPath = '/'

  var connect = require('connect')
  var serveStatic = require('serve-static')
  const app = connect()

  app.use(
    publicPath,
    serveStatic('./dist', {
      index: ['index.html', '/']
    })
  )

  app.listen(port, function () {
    console.log(chalk.green(`> Preview at  http://localhost:${port}${publicPath}`))
    if (report) {
      console.log(chalk.green(`> Report at  http://localhost:${port}${publicPath}report.html`))
    }

  })
} else {
  run(`npm run build:self ${args}`)
}

最后执行 npm run preview 或者 yarn preview就可以在本地启动一个服务器,跑打包后的项目

;