开发单页面应用(vue,react,angular),为了提高开发效率,使用webpack作为编译工具和搭建热模块替换(HMR)环境,在项目部署时候这套环境不适合生产环境,所以需要把开发的文件用webpack打包后部署到生产环境,部署的时候需要注意下面几点

加密和压缩

使用webpack的uglifyJS插件可以加密和压缩js文件,同时也可以压缩css文件,常用的配置如下

module.exports = {
 plugins: [
    new webpack.optimize.UglifyJsPlugin() 
 ]
}

声明webpack打包环境变量

module.exports = {
 plugins: [
  new webpack.DefinePlugin({
    'process.env.NODE_ENV': JSON.stringify('production')
  })
 ]
}

关闭source map功能

在webpack配置文件中把devtool选项删掉或者使用cheap-module-source-map,最简单的直接使用webpack -p来编译打包生产环境文件

资源文件路径

在css引入图片有时候打包后的路径不对,可以通过output.publicPath修改资源文件的公共路径

url路径

在地址栏手动输入前端路由会在服务器寻找url的对应路由,通常会导致404,所以需要在服务器做相应的配置

nginx服务器

使用 try_files 指令

server {
  ...
  location / {
    try_files $uri /index.html;
  }
}

express服务器

配置静态文件服务和路径指向index.html

const express = require('express')
const path = require('path')
const port = process.env.PORT || 8080
const app = express()

// serve static assets normally
app.use(express.static(__dirname + '/public'))

// handle every other route with index.html, which will contain
// a script tag to your application's JavaScript file(s).
app.get('*', function (request, response){
  response.sendFile(path.resolve(__dirname, 'public', 'index.html'))
})

app.listen(port)
console.log("server started on port " + port)

 

本文为原创,未经授权,禁止任何媒体或个人自媒体转载
商业侵权必究,如需授权请联系[email protected]