使用express配置前端代码服务器

咱们知道使用webpack打包vue项目后会生成一个dist文件夹,dist文件夹下有html文件和其余css、js以及图片等,那么打包后的文件该如何正确运行呢?javascript

  假若直接打开html文件,会报以下错误:css

  那么该如何运行呢?其实能够将生成的dist文件部署到 express 服务器上运行。html

  (1)、安装express-generator生成器。vue

     npm install express-generator -g // 也可以使用cnpm比较快 java

  

  (2)、建立一个express项目。webpack

     express expressName // expressName是项目名 web

 

  (3)、进入项目目录,安装相关项目依赖。express

     cd expressName npm

     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打包的时候记得把资源文件指向这个目录,添加新路由便可

相关文章
相关标签/搜索