Write a server code to deploy the "vue e-commerce background management system" to go online and package

I will use cnpm as the code format throughout the blog post , for the sake of copying, it is fast ! You need to know that the node installation package comes with npm , and npm downloads cnpm before you can use cnpm

Today's goals:

 1. Launch the vue e-commerce background management project

 2. Manually build the server and mount it (node)

 3. Packaging optimization completed and launched

Early review     

Finally someone can talk about the server so bluntly How to operate, you will gain a lot after watching! https://blog.csdn.net/m0_57904695/article/details/122938095

introduce:

This is the background management project I wrote. Today is to operate it (150,000-word detailed tutorial). I will paste it . If you only look at the packaging and deployment, go ahead and fast-forward.

Combining server + back-end + front-end to complete the Vue project background management system Back-end + front-end, complete the vue project background management system https://blog.csdn.net/m0_57904695/article/details/122648464?spm=1001.2014.3001.5502 Before this, I wrote an article to deploy nginx, from writing code to mobile phones The app is extremely detailed, and you will gain a lot after watching it! Mainly vant, mobile terminal

Step by step, step by step from code to, packaged into mobile App, uploaded to nginx server (Vue project) project) https://blog.csdn.net/m0_57904695/article/details/122500485?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522164506544716780265430357%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fblog .% 2522% 257D & request_id = 164506544716780265430357 & biz_id = 0 & utm_medium = distribute.pc_search_result.none-task-blog-2 ~ blog ~ first_rank_ecpm_v1 ~ rank_v31_ecpm-1-122500485.nonecase & utm_term =% E4% B8% 8A% E7% BA% BF & spm = 1018.2226.3001.4450


Check the package size for the first time (7.09MB)

 

 view.config.js

  • If not, create a new one, vue.config.js explains: it is to modify the default configuration items of webpack

important! Steps 1-17 Search for steps through ctrl+f. There are commands to download dependencies in the code comments. To download the dependencies, the following is the code. You must download the dependencies before you can use them.

// 1-17步骤
// 3 加载path模块和定义resolve方法, 把相对路径转换成绝对路径
const path = require('path')
const resolve = dir => path.join(__dirname, dir)

// 5 安装去除log包  cnpm install uglifyjs-webpack-plugin --save-dev
//6引入去除log文件
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const isProduction = process.env.NODE_ENV === 'production';

// 13 对资源文件进行压缩引入
const CompressionWebpackPlugin = require('compression-webpack-plugin')
    // 8 使用externals设置排除项 
const externals = {
        //这里如果写的不对,dist/index打开会报xx未定义, 
        // 模块名称和作用域名(对应的是window里面的全局变量名)
        // 模块名称和作用域名一定要写对,不然不是报未定义就是打包cdn引入不进去 !!!
        vue: 'Vue',
        "element-ui": "element",
        'vue-router': 'VueRouter',
        axios: 'axios',
        lodash: '_',
        echarts: 'echarts',
        nprogress: 'NProgress',
        'vue-quill-editor': 'VueQuillEditor',

    }
    // CDN外链,会插入到index.html中
const cdn = {
    // 开发环境
    dev: {
        css: [],
        js: []
    },
    // 生产环境
    build: {
        // element在vue下,顺序不对也会报错
        css: [
            "https://cdn.staticfile.org/element-ui/2.8.2/theme-chalk/index.css",
            'https://cdn.staticfile.org/nprogress/0.2.0/nprogress.min.css',
            'https://cdn.staticfile.org/quill/1.3.4/quill.core.min.css',
            'https://cdn.staticfile.org/quill/1.3.4/quill.snow.min.css',
            'https://cdn.staticfile.org/quill/1.3.4/quill.bubble.min.css',
        ],
        js: [
            "https://cdn.staticfile.org/vue/2.5.22/vue.min.js",
            "https://cdn.staticfile.org/element-ui/2.8.2/index.js",
            "https://cdn.staticfile.org/vue-router/3.0.1/vue-router.min.js",
            "https://cdn.staticfile.org/axios/0.18.0/axios.min.js",
            "https://cdn.staticfile.org/lodash.js/4.17.11/lodash.min.js",
            "https://cdn.staticfile.org/echarts/4.1.0/echarts.min.js",
            "https://cdn.staticfile.org/nprogress/0.2.0/nprogress.min.js",
            "https://cdn.staticfile.org/quill/1.3.4/quill.min.js",
            "https://cdn.jsdelivr.net/npm/[email protected]/dist/vue-quill-editor.js",
        ]
    }
}
module.exports = {
    // 1
    publicPath: './', // 静态资源路径(默认/,打包后会白屏)
    // 2
    productionSourceMap: false, //错误映射,关闭会减少一半体积


    devServer: {
        hotOnly: true, // 热更新
        open: true
    },
    // 4 添加别名
    chainWebpack: config => {
        config.resolve.alias
            .set('@', resolve('src'))
            .set('assets', resolve('src/assets'))
            .set('api', resolve('src/api'))
            .set('views', resolve('src/views'))
            .set('components', resolve('src/components'))
            // 10  添加CDN参数到htmlWebpackPlugin配置中
            // 11  在pubilc/index 中配置  我放在最下面了
            // 12 cnpm i compression-webpack-plugin -D  对资源文件进行压缩
        config.plugin('html').tap(args => {
                if (isProduction) {
                    args[0].cdn = cdn.build
                } else {
                    args[0].cdn = cdn.dev
                }
                return args
            })
            // 16 配置图片压缩
        config.module
            .rule('images')
            .use('image-webpack-loader')
            .loader('image-webpack-loader')
            .options({
                bypassOnDebug: true
            })
            .end()
    },
    // 7 使用去除log
    configureWebpack: config => {
        const plugins = [];
        if (isProduction) {
            // 9 配置cdn
            config.externals = externals
                // 配置cdn

            plugins.push(
                    new UglifyJsPlugin({
                        uglifyOptions: {
                            output: {
                                comments: false, // 去掉注释
                            },
                            warnings: false,
                            compress: {
                                drop_console: true,
                                drop_debugger: false,
                                pure_funcs: ['console.log'] //移除console
                            }
                        }
                    }),
                    // 14 对资源文件进行压缩引入进行配置:
                    new CompressionWebpackPlugin({
                        filename: '[path].gz[query]',
                        algorithm: 'gzip',
                        // test: /\.js$|\.html$|\.json$|\.css/,
                        test: /\.js$|\.json$|\.css/,
                        threshold: 10240, // 只有大小大于该值的资源会被处理
                        minRatio: 0.8, // 只有压缩率小于这个值的资源才会被处理
                        // deleteOriginalAssets: true // 删除原文件
                    })
                    // 15 安装图片压缩 cnpm install image-webpack-loader --save-dev 容易安装不上
                    // 若安装过 image-webpack-loader 先卸载 !!!
                    // npm 安装的npm 则npm 移除
                    // npm uninstall image - webpack - loader
                    //如果yarn安装的,则yarn 移除
                    // yarn remove image - webpack - loader

                ),
                // 17公共代码抽离
                config.optimization = {
                    splitChunks: { // 分割代码块
                        cacheGroups: {
                            vendor: { //第三方库抽离
                                chunks: 'all',
                                test: /node_modules/,
                                name: 'vendor',
                                minChunks: 1, //在分割之前,这个代码块最小应该被引用的次数
                                maxInitialRequests: 5,
                                minSize: 0, //大于0个字节
                                priority: 100 //权重
                            },
                            common: { //公用模块抽离
                                chunks: 'all',
                                test: /[\\/]src[\\/]js[\\/]/,
                                name: 'common',
                                minChunks: 2, // 在分割之前, 这个代码块最小应该被引用的次数
                                maxInitialRequests: 5,
                                minSize: 0, //大于0个字节
                                priority: 60
                            },
                            styles: { //样式抽离
                                name: 'styles',
                                test: /\.(sa|sc|c)ss$/,
                                chunks: 'all',
                                enforce: true
                            },
                            runtimeChunk: {
                                name: 'manifest'
                            }
                        }
                    }
                }
        }
    },
}

important! ! ! Assign the above code to the vue.config.js file, and configure the cdn according to your own project

legend:

You can search and configure BootCDN according to the cdn link required by your own project  - Bootstrap Chinese Network Open Source Project Free CDN Acceleration Service

CDNs required for this project


    <!-- nprogress 的样式表文件 -->
    <link rel="stylesheet" href="https://cdn.staticfile.org/nprogress/0.2.0/nprogress.min.css" />
    <!-- 富文本编辑器 的样式表文件 -->
    <link rel="stylesheet" href="https://cdn.staticfile.org/quill/1.3.4/quill.core.min.css" />
    <link rel="stylesheet" href="https://cdn.staticfile.org/quill/1.3.4/quill.snow.min.css" />
    <link rel="stylesheet" href="https://cdn.staticfile.org/quill/1.3.4/quill.bubble.min.css" />
    <!-- element-ui 的样式表文件 -->
    <link rel="stylesheet" href="https://cdn.staticfile.org/element-ui/2.8.2/theme-chalk/index.css" />

    <script src="https://cdn.staticfile.org/vue/2.5.22/vue.min.js"></script>
    <script src="https://cdn.staticfile.org/vue-router/3.0.1/vue-router.min.js"></script>
    <script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script>
    <script src="https://cdn.staticfile.org/lodash.js/4.17.11/lodash.min.js"></script>
    <script src="https://cdn.staticfile.org/echarts/4.1.0/echarts.min.js"></script>
    <script src="https://cdn.staticfile.org/nprogress/0.2.0/nprogress.min.js"></script>
    <!-- 富文本编辑器的 js 文件 -->
    <script src="https://cdn.staticfile.org/quill/1.3.4/quill.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue-quill-editor.js"></script>

    <!-- element-ui 的 js 文件 -->
    <script src="https://cdn.staticfile.org/element-ui/2.8.2/index.js"></script>

After the cdn is configured, add the following code to public/index.html

 <!-- 使用CDN的CSS文件 -->
    <% for (var i in
        htmlWebpackPlugin.options.cdn&&htmlWebpackPlugin.options.cdn.css) { %>
        <link href="<%= htmlWebpackPlugin.options.cdn.css[i] %>" rel="preload" as="style" />
        <link href="<%= htmlWebpackPlugin.options.cdn.css[i] %>" rel="stylesheet" />
        <% } %>
            <!-- 使用CDN加速的JS文件,配置在vue.config.js下 -->
            <% for (var i in
        htmlWebpackPlugin.options.cdn&&htmlWebpackPlugin.options.cdn.js) { %>
                <script src="<%= htmlWebpackPlugin.options.cdn.js[i] %>"></script>
                <% } %>

You need to configure environment variables, go online, and run npm run build to get the production environment online, so you need to configure the online URL. The third picture below

Configure environment variables: Refer to Vue to configure multiple environment variables, it turns out that this is the case


 

You can view the packaging report by adding --report after build 

// package.json 
 "scripts": {
        "serve": "vue-cli-service serve --open",
        "build": "vue-cli-service build --report"
    },

  Now that it has been configured , we are rerunning the packaging command to check the size of the dist file

 After the packaging is completed, this packaging report is useless and can be deleted.

The project is online

 Create a server through node and write a simple server yourself

1: Create a folder server cd in the root directory to enter the sever directory

2: Enter the commandnpm init -y 一路回车 初始化得到package.json

3: After initializing the package, enter the command cnpm i express -S下载依赖

4: Copy distthe folder and paste it serverinto

5: serverCreate a app.jsfile in the folder and write the code as follows

//学过node都知道,只是导入express,我们刚才下载好了
const express = require('express')
// 将方法赋值给app
const app = express()
//使用中间件加载静态资源./dist,我们需要将dist粘贴到同级目录
app.use(express.static('./dist'))
//监听端口8888,端口号随你写建议在3000以上不予默认端口冲突,就类似酒店的房门号,你我
//都是汉子可不能住一间,
app.listen(8888,()=>{
    console.log("服务器成功运行")
})

6: Type in the terminal node app.js  运行服务器 

Effect picture:


I myself enter the url in the browser: http://localhost:8888/   You need to access the two of us on the same local area network, enter my computer ip: port number as shown below:

This is deployed on the server we wrote ourselves. You enter my computer id and port. We are in the same local area network and you can also access this project. This is my computer acting as the server, but you have to keep the terminal open, you can borrow it Plugin, open a process, so I close the terminal, you can still access the project

 

Use pm2 to manage the application to start the process 

 Open the terminal of the server folder, enter the command: cnpm i pm2 -g Start the project
with pm2 , enter the command in the terminal: pm2 start app.js --name Customize the name to view the project list Command: pm2 ls Restart the project: pm2 restart since define name stop project: pm2 stop custom name delete project: pm2 delete custom name




 

enable gzip compression

Open serverthe terminal of the folder, enter the command: cnpm i compression -D
open app.js, write the code: 

//学过node都知道,只是导入express,我们刚才下载好了
const express = require('express')
const compression = require('compression')
    // 将方法赋值给app
const app = express()
app.use(compression())
    //使用中间件加载静态资源./dist,我们需要将dist粘贴到同级目录
app.use(express.static('./dist'))
    //监听端口8888,端口号随你写建议在3000以上不予默认端口冲突,就类似酒店的房门号,你我
    //都是汉子可不能住一间,
app.listen(8888, () => {
    console.log("服务器成功运行")
})

At this point, the project has been successfully packaged and deployed to the server,

Conclusion:

I hope everyone is doing well, there are no classes that can't be added, and bugs can't be fixed.

Guess you like

Origin blog.csdn.net/m0_57904695/article/details/122977868