Vue 2.x + Webpack 3.x + Nodejs multi-page Project Framework (previous--pure front-end multi-page)

Source: Internet
Author: User
Tags npm scripts

Vue 2.x + Webpack 3.x + Nodejs multi-page Project Framework (previous--pure front-end multi-page)

@ (HTML/JS)

In general, it is better to use Vue as a single-page application, but there are additional benefits to using multiple pages in special cases. For example, the multi-webview architecture of the hand Q, the newly opened page facilitates the right stroke of the iOS and avoids the refresh of the page when it returns.
So here's a look at how to configure a project framework that implements a multi-page approach. Here is the beginning, first with the simplest pure front-end multi-page as an example, the ultimate goal is to complete the node. JS Multi-page straight out + front-end isomorphic structure.

This article source code: HTTPS://GITHUB.COM/KENKOZHENG/HTML5_RESEARCH/TREE/MASTER/VUE-MULTIPAGES-WEBPACK3

This document is also the step to implement a pure front-end multi-page

    • VUE-CLI Creating a framework
    • Analyze prototype project Configurations
    • Multi-page transformation
1 utilization vue-cliBuilding a basic framework

VUE-CLI is an official scaffolding tool that quickly builds prototype projects.

    • Install VUE-CLI:npm i -g vue-cli
    • Initialize the project:vue init <template-name> <project-name>

Here I choose the simplest template:webpack-simple. Create the project directory first and then run it in the directory, all the way vue init webpack-simple down.

We will then get a directory structure like this:
!

    • BABELRC is the Babel configuration file, detailed look at Babel's own introduction
    • Editorconfig control the text style of the editor and the like, you can delete
    • Gitignore is the configuration of git
    • Index.html is a single-page HTML
    • Webpack.config.js has differentiated the development environment or production environment, production environment plus uglify confusion
    • The SRC directory includes the page's Vue single file (component) and the main entry main.js
2 Running the Analysis prototype project

Vue-cli Project.json, webpack configuration and NPM scripts are ready, great. We only need two steps to run the project

    # install dependencies    npm install            # serve with hot reload at localhost:8080    npm run dev        # build for production with minification    npm run build

Running NPM Run dev can start the default 8080 port listening server, with Webpack hot update family bucket, very convenient.
However, we need to understand all the source code in order to do the next step.

>.babelrc

The configuration of the details is numerous, the prototype project uses the Env plugin, and the module related syntax is not escaped (left to webpack processing)

    ["env", { "modules": false }]
>webpack.config.js
  entry: './src/main.js',  output: {    path: path.resolve(__dirname, './dist'),    publicPath: '/dist/',    filename: 'build.js'  }

Entry can specify the file to be packaged as an array or an object or a single string;
Output specifies the information that is exported after packaging. It is best to refer to the official documentation, it is not possible to see the source code, a variety of online articles may be wrong, including my this article. Official Document: https://doc.webpack-china.org/concepts/output/
The key point is that filename can be used with [name]. [Hash:8] and other keywords in the way of implementation of the entry input and dynamic changes in the file name, follow-up will be used.
Path and publicpath need to be differentiated.

    • Path refers to the file directory that is exported after packaging
    • Publicpath refers to the file generated in path, the corresponding extranet access address, needs to be completed according to the actual deployment of the project after the final release, development and production of the two environments may not be the same path. For example, if you pack a picture into the./dist/img1.jpg, then the reference path in the response JS becomes/dist/img1.jpg. Two parameters to match well.
    module: {        rules: [          {            test: /\.css$/,            use: [              'vue-style-loader',              'css-loader'            ],          }            ...            {            test: /\.(png|jpg|gif|svg)$/,            loader: 'file-loader',            options: {              name: '[name].[ext]?[hash]'            }          }        ]    }

Look at module, here from the beginning of the 2.x changed the format, at a glance, is the various files should use what loader to load processing.
The main need to care about the last file-loader,name to match with the previous Publicpath, in addition to writing filenames can also write directories, Webpack will automatically create directory storage files.

  resolve: {    alias: {      'vue$': 'vue/dist/vue.esm.js'    },    extensions: ['*', '.js', '.vue', '.json']  },  devServer: {    historyApiFallback: true,    noInfo: true,    overlay: true  },  performance: {    hints: false  },  devtool: '#eval-source-map'

Resolve's alias is intended to be an alias mapping that can be dynamically replaced with the corresponding string when vue$ appears in the code.
Devserver controls the behavior of the Webpack's own hot-update server, such as modifying the port. Run with NPM script: webpack-dev-server --open --hot . It is important to note that Devserver uses MEMORY-FS and does not write directly to the file system. Mate Writefileplugin can force writes. If you do not use Devserver debugging, such as fiddler substitution, you need to force the file system to be written.
Performance can skip first.
Devtool is to control the generated source code Source-map function, according to the default, the specific use of the principle is simple, is the browser support of the confusion after the code map to the source file mapping table.

process.env.NODE_ENV === 'production'new webpack.optimize.UglifyJsPlugin({      sourceMap: true,      compress: {        warnings: false      }    })

Finally, the environment variables are judged, if the production is released, plus the Uglify plugin. The parameter settings here refer to the Uglify plugin itself.
setting of the environment variable, using the Cross-env tool, run the settings in the NPM scriptcross-env NODE_ENV=production

>app.vue and Index.html

These two are very basic VUE functions. The concern is that there is now only one index.html, and the function of index.html is a single pure introduction to JS. How HTML is reused when you do a long page is an issue to consider.

3 Multi-page retrofit

Understanding the capabilities of the prototype project, the next things to do include:

    • Create a multi-page project directory, creating multiple Vue
    • Webpack Multi-entry configuration
    • Reuse html/automatically generate HTML
    • Some optimization of the actual project
> Create multiple pages

>webpack Multi-entry configuration
var pages = ['page1', 'page2'];         //可以根据项目情况,自动分析目录文件生成var entry = {};pages.forEach(function (pageName) {    entry[pageName] = `./src/pages/${pageName}/main.js`;});//////////////module.exports = {    entry: entry,    output: {        path: path.resolve(__dirname, `./dist/`),        publicPath: process.env.NODE_ENV === 'production' ? '/' : '/dist/',       //发布后在线访问的url。dev模式下,使用的是express在当前项目根目录启动        filename: `[name].js`   //'[name].[chunkhash].js', '[name].[hash:8].js'    }        ...

The main is that filename uses a dynamic configuration method, which is mapped according to the entry key.

> Automating HTML generation

Because the index.html content is simple, we don't need to copy each page. and others have already thought of this, so there is html-webpack-plugin .
The usual, NPM, install it.

Then, modify the Webpack configuration

pages.forEach(function (pageName) {    module.exports.plugins.push(        new HtmlWebpackPlugin({            title: pageName,            filename: `${pageName}.html`,            template: `./src/pages/tpl.html`,            chunks: [pageName],            inlineSource: '.(js|css)$' // embed all javascript and css inline。结合HtmlWebpackInlineSourcePlugin才有效果        })    );});

Automatically build multiple Htmlwebpackplugin instances into the configuration, based on the configuration of the pages array.
As the name implies, the configuration is relatively simple, detailed reference official website: https://github.com/jantimon/html-webpack-plugin
Inlinesource is a special field, which is followed up.

At this point, you can run the project, and in dev mode, Webpack will generate Page1 and Page2 each time it is automatically packaged.

> Some project optimization

Packaging for global shared CSS
In the page main.js, the direct import will eventually be converted to the HTML-injected JS code.

import '../../css/base.css'

Picture Packaging file Name management

            {                test: /\.(png|jpg|gif|svg)$/,                loader: 'file-loader',                options: {                    name: 'img/[name].[hash:8].[ext]'    //自动hash命名图片等资源,并修改路径。路径需要根据项目实际情况确定。语法参考:https://doc.webpack-china.org/loaders/file-loader/                }            }

Often the picture is long after the release of the cache, it is a good way to add a hash in the file name to make a version distinction. In addition, using a separate directory makes it easier for the CDN to set the cache time.

HTML, JS, CSS packaged together to reduce requests
Multi-page determines that each page is not too large, for the current mobile internet, packaged HTML will be more than a number of JS request faster.
This is what we need to use HtmlWebpackInlineSourcePlugin , which is the Inlinesource field we just mentioned.

    module.exports.plugins.push(        new HtmlWebpackInlineSourcePlugin() //内联css、js。配合HtmlWebpackPlugin    );
4 Running Up

Download code: HTTPS://GITHUB.COM/KENKOZHENG/HTML5_RESEARCH/TREE/MASTER/VUE-MULTIPAGES-WEBPACK3

 npm i npm run dev

Browser access http://localhost:8088/dist/page1.html and http://localhost:8088/dist/page2.html look at it.

Next: Multi-page vuessr+ Hot update server

Vue 2.x + Webpack 3.x + Nodejs multi-page Project Framework (previous--pure front-end multi-page)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.