Webpack with Vue.js for complete Single-page demo

Source: Internet
Author: User

This article is mainly I researched the single page application of Webpack+vue.js before development, because the need to use Node's npm, so make sure that node is installed, it is recommended to install the latest stable version of the Website. And in the project need to load some NPM package, because NPM server abroad, we may download the process is slow, it is recommended to use Ali's mirror CNPM installation, 10 minutes Real-time update NPM Image. The specific download configuration reference Ali's CNPM official Website. This article is just to discuss how to use Webpack with Vue.js to do a single page application, specifically about the content of Vue inside how to write not in the scope of this Article.

1. Define the basic catalogue of our Demo

├── README.md           ├── index.html         // 项目入口文件├── package.json       // 项目配置文件├── src                // 生产目录│   ├── vue         // 组件│ | ├──home.vue│ | ├──blog.vue│ | ├──about.vue│ | ├──topic.vue│ ├── components // 各种组件│ ├── views // css文件│ ├── scss //scss文件│ └── main.js // Webpack 预编译入口└── webpack.js // Webpack 配置文件
2. Configure our Webpack.js file

You need to master a command before you describe how to configure this command means that this npm install <模块> --save-dev name means that we have installed this package and have written its basic information to the Directory's Package.json File. There is also a command that we run CNPM install automatically to download the package that is written in Package.json.

The Webpack configuration file we need to use four NPM modules are: path , webpack , extract-text-webpack-plugin , Vue-loader Remember to first download the package in the Require command to bring in

//node的路径模块var path=require(‘path‘);//我们是webpack当然要引入这个var webpack = require(‘webpack‘);//这个是构建页面资源的插件var ExtractTextPlugin = require(‘extract-text-webpack-plugin‘);//因为我们是vue.js的应用,把各个组件当做一个页面.vue后缀,所以引入这个可以编译這些文件var vue = require("vue-loader");

well, We've introduced the modules we need, and then we'll define some of the folder paths we'll use Next.

//__dirname是node里面的一个变量,指向的是当前文件夹目录var ROOT_PATH = path.resolve(__dirname);//这个我们的文件入口,等下我们就会从main.js这个文件作为入口var APP_PATH = path.resolve(ROOT_PATH, ‘src/main.js‘);//这个是文件打包出来的输出路径var BUILD_PATH = path.resolve(ROOT_PATH, ‘build‘);

The basic file path we've defined, and we're going to use extract-text-webpack-plugin this plugin.

var plugins = [  //提公用js到common.js文件中  new webpack.optimize.CommonsChunkPlugin(‘common.js‘),  //将样式统一发布到style.css中 new ExtractTextPlugin("style.css"), // 使用 ProvidePlugin 加载使用率高的依赖库 new webpack.ProvidePlugin({ $: ‘webpack-zepto‘ })];

Next is the focus of Webpack loader,webpack the idea is to load each static resource file as a module, we need to do some configuration, where we need to compile the Css,sass module, more than we also need to install ' Css-loader ', ' Style-loader ', ' node-sass ', ' MD5 '

Module.exports = {The entrance to the file can also be written in the form of most groups, specifically extending entry:[app_path],Output output:{//output path path:build_path, //packaged js named filename: Build.js//point to the async-loaded path publicpath: __dirname + '/build/ ',// Naming rules for Non-master files, add cache to MD5 chunkfilename: ' [id].build.js? [chunkhash] 40000 '} '},//this Special note, Vue advocates that a component be treated as a page, so it is possible to write html,style,javascript on a page, or to introduce and write Scss file vue: {css:ExtractTextPlugin.extract ("css"), sass: Extracttextplugin.extract ("css!sass-loader")}, plugins:plugins}       
3. Configure our Portal file Main.js

Here we need three NPM modules, vue,vue-router,vue-resource three modules, we install in turn and then introduce

//vue的应用当然要引,等下要用它来注册var Vue = require(‘vue‘)//这个是路由,spa应用必要哦var VueRouter = require(‘vue-router‘);//这个是类似ajax请求,肯定要拉去数据啦,所以也下载吧var VueResource = require(‘vue-resource‘);

Declare and register an empty component in Vue

Vue.use(VueRouter);Vue.use(VueResource);var app = Vue.extend({});

Instantiate Vuerounter

var router = new VueRouter({    // 当hashbang的值为true时,所有的路径都会被格式化已#!开头, hashbang: true, history: false, saveScrollPosition: true, transitionOnLoad: true});

Next write down our routing path, You can also write the route separately in a file, our side is just a demo so write together, matter, about this route can be specific reference Vue-router document HTTP://ROUTER.VUEJS.ORG/ZH-CN ..., will be very detailed.

It is necessary here that Webpack provides an asynchronous load function that works with Vue-router routing, and when which component needs to be rendered, it loads the components it relies on and asynchronously loads it in. Isn't it great.

Router.map ({‘/‘:{Home Component:function(resolve) {Require (['./vue/home.vue '],resolve)},'/home ': {name:' Home ',Home Component:function(resolve) {Require (['./vue/home.vue '],resolve)},'/blog ': {name:' Blog ',Blog List component:function  (resolve) {require ([/vue/blog.vue '],resolve)}}, / Blog/topic ': {name:  ' topic ', //article details component: function  (resolve) { require ([/about ': {name:  ' about ', //on component: function  (resolve) {require (["/vue/about.vue '],resolve)}}})      

Add a code to test whether access routing access is successful

router.afterEach(function (transition) {  console.log(‘成功浏览到: ‘ + transition.to.path)})

finally, We register for the Vue.

"#app");
4. Populating the structure of the index.html file

<router-view> is used to render matching components based on Vue's dynamic component System. Our index.html structure is like This.

<! DOCTYPE html><Htmllang="en" ><Head><Metacharset="UTF-8" ><Title> Personal Station</Title><LinkRel="stylesheet"href="./build/style.css" ></Head><Body><DivId= "app" > <router-view></router-view> </ div> <script src= "/build/common.js" >< Span class= "hljs-tag" ></script> < script src= "/build/build.js" ></script> </body></ html>             
5. How to write a component

About components, Vue advocates a module to write a specific component such as list components can be list.vue, and then load specific components according to the route, the components can also be referenced to each other, specific reference vue Document.

In order to facilitate our testing, we take home as an example, other components are similar, easy to wait for testing, and so on, and so the project can completely run up you to add components inside the Content.

<template>     <div>home</div></template><script> // js</script><style> /*style*/</style>
6. Running Webpack

About a single page of the general framework we have been set up, and now directly run Webpack will be able to load the files Out. Then open the index.html Direct test just FINE. More detailed demo has been submitted to GitHub on the demo, as well as I use Webpack+vue+es6+sass technology stack refactoring cnode Chinese web single page application, interested can onlookers, welcome star.

7. Development Model

In the actual development process, we certainly do not change the save, and then run the Webpack command, so it is too troublesome, so we used a hot replacement, webpack-dev-server this package, installed this package after the Pack.json Plus

"scripts": {    "start": "webpack-dev-server --hot --inline"}

And put the webpack.config.js that we've configured Before.

// 指向异步加载的路径 publicPath : __dirname + ‘/build/‘;

Replaced by

// 指向异步加载的路径 publicPath : ‘/build/‘;

Why did you do it? Because we used webpack to load the component asynchronously locally, and we used the hot replace is the address delegated to the http://localhost:8080/port, so to remove the __dirname (point to the local root), everything is ready to complete, Next Run NPM start directly, then open Http://localhost:8080/can access, try to modify the content to save can see the page real-time in the refresh, is not a lot of development time saved!

About VUE-CLI

The original author of Vue.js to make it easier for us to spend time on the Project. configure these automated build tools, out of a VUE-CLI scaffolding that automatically generates a series of basic configurations of the Project. Vue-cli's GitHub address is https://github.com/vuejs/vue-cli, and interested children's shoes can be understood below.

Webpack with Vue.js for complete Single-page demo

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.