我们知道使用webpack打包vue项目后会生成一个dist文件夹,dist文件夹下有html文件和其他css、js以及图片等,那么打包后的文件该如何正确运行呢?
倘若直接打开html文件,会报如下错误:
那么该如何运行呢?其实可以将生成的dist文件部署到 express 服务器上运行。
(1)、安装express-generator生成器。
npm install express-generator -g // 也可使用cnpm比较快
(2)、创建一个express项目。
express expressName // expressName是项目名
(3)、进入项目目录,安装相关项目依赖。
cd expressName
npm install // 或cnpm install
(4)、此时生成的项目目录应该是这样的:
(5)、将dist文件夹下的所有文件复制到express项目的publick文件夹下面,然后运行 npm start 来启动express项目。
(6)、打开浏览器,输入localhost:3000就可以看到效果了。
express配置多个vue项目
关键配置
vue: 在config/index.js文件中,如下配置
build: { // Template for index.html index: path.resolve(__dirname, '../dist/index.html'), // Paths assetsRoot: path.resolve(__dirname, '../dist'), assetsSubDirectory: 'static', assetsPublicPath: '/action/', //关键配置,资源目录要摆在对应服务器上的目录下,如果使用express,还需要配置一下路由 //具体方法是在app.js里面加上app.use('/h5/xxx/', express.static(__dirname+'/public/xxx')); xxx=action //打包出来的项目放在express的public/action目录下,文件存在请替换文件 /** * Source Maps */ productionSourceMap: true, // https://webpack.js.org/configuration/devtool/#production devtool: '#source-map', // Gzip off by default as many popular static hosts such as // Surge or Netlify already gzip all static assets for you. // Before setting to `true`, make sure to: // npm install --save-dev compression-webpack-plugin productionGzip: false, productionGzipExtensions: ['js', 'css'], // Run the build command with an extra argument to // View the bundle analyzer report after build finishes: // `npm run build --report` // Set to `true` or `false` to always turn it on or off bundleAnalyzerReport: process.env.npm_config_report }
打开express根目录的app.js文件,加上
app.use('/h5/xxx/', express.static(__dirname+'/public/xxx')),然后
打包出来的webpack项目放在express的public/action目录下,文件存在请替换文件
本例子是在express中配置了一个/h5/action的网页
可以根据以上方法配置自己的网页,可以配置多个,目录资源目录统一在public中新建文件夹,然后vue打包的时候记得把资源文件指向这个目录,添加新路由即可