首先在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就可以在本地啟動一個伺服器,跑打包後的專案