The construction process _javascript skill of vue2.0+webpack environment

Source: Internet
Author: User
Tags emit

This paper introduces the construction process of vue2.0+webpack environment.

1. First create a new directory Vue-wkdemo, this is our project directory. Execute the NPM init command to generate the Package.json file. After you perform NPM init, you will be prompted to fill in some project information, always return to the default, or directly execute NPM init-y to skip the inquiry step directly.

2. Installation Project Dependencies

NPM Install Webpack webpack-dev-server vue-loader vue-html-loader css-loader vue-style-loader vue-hot-reload-api
Babel-loader babel-core babel-plugin-transform-runtime babel-preset-es2015 babel-runtime@5--save-dev
NPM Install Html-webpack-plugin--save-dev
npm install vue--save

3. New Portal file Index.js, file location placed as: Vue-wkdemo->app->index->index.js

Import Vue from ' Vue '
import favlist from './components/favlist.vue '
Vue.config.debug = true;//Open Error prompt
Window.onload = function () {
new Vue ({
el: ' #app ',
components: {
' my-component ': Favlist
}
});
}

4. Build index.html template, the file location is placed as: vue-wkdemo->app->index->index.html

<! DOCTYPE html>
 
 

5. Build the Vue component Favlist.vue, the file is placed as: Vue-wkdemo->app->components->favlist.vue

<template id= "Template-home" >
<div>
<div v-for= "N in ten" >div</div>
</div >
</template>
<style> body
{
color:red;
}
</style>

6. Build Webpack.config.js, file placed as: Vue-wkdemo->build->webpack.config.js

Path Module
var path in Nodejs = require (' path ');
var htmlwebpackplugin = require (' Html-webpack-plugin ')
module.exports = {
//portal file, Path.resolve () method, Can be combined with our given two parameters to finally generate an absolute path, the final point is our index.js file
entry:path.resolve (__dirname, '. /app/index/index.js '),
//Output configuration output
: {
//export path is myproject/output/static
path:path.resolve (__ DirName, '. /output/static '),
publicpath: ' static/',
filename: ' [name].[ Hash].js ',
chunkfilename: ' [id].[ Chunkhash].js '
},
resolve: {
extensions: [', '. js ', '. Vue '],
alias: {
' vue ': ' vue/dist/ Vue.js '
}
},
module: {
loaders: [
///using Vue-loader loading. Vue end of file
{
test:/\.vue$/,< C25/>loader: ' Vue '
},
{
test:/\.js$/,
loader: ' babel?presets=es2015 ',
exclude:/node_ Modules/
}
]
},
favlist: {
loaders: {
js: ' Babel '
}
},
plugins: [
New Htmlwebpackplugin ({
filename: ' ...) /index.html ',
template:path.resolve (__dirname, ' ...) /app/index/index.html '),
inject:true
})
]
}

7. Run Build command:

' Webpack–display-modules–display-chunks–config build/webpack.config.js '

You can see the output file:

8. Here, our directory structure is:

Run output->static->index.html This file, the process encountered a variety of pits (omitted hundreds of words ...). )

Finally saw the result!!!

9. The problem is that each time you need to run the build command to see the changed code effect, this is very inefficient, so you also need to install Webpack-dev-middleware middleware and Webpack-hot-middleware middleware

NPM Install Webpack-dev-middleware webpack-hot-middleware--save-dev

Also need to install Express

NPM Install Express--save-dev

Introduction to the next Webpack-dev-middleware middleware, which is a simple package for webpack, it can be connected to the server to serve those launched from Webpack files, it has a few advantages:

1, will not write files to the hard disk, but in memory, note that we build the project is actually to the hard disk to write files.

2, when the file changes, the middleware will not serve the old package, you can directly refresh the browser can see the latest effect, so you do not have to wait for the build time, WYSIWYG.

Create a Dev-server.js file in the build directory and write to the content:

Introducing the necessary modules
var Express = require (' Express ')
var webpack = require (' Webpack ')
var config = require ('./webpack . config ')
///Create a Express instance
var app = Express ()
//Call Webpack and pass configuration past
var compiler = webpack (config)
//using Webpack-dev-middleware middleware
var devmiddleware = require (' Webpack-dev-middleware ') (compiler, {
PublicPath:config.output.publicPath,
stats: {
colors:true,
chunks:false
}
})
// Register middleware
App.use (devmiddleware)
//Monitor port 8888, turn on server
app.listen (8888, function (err) {
if (err) {
Console.log (Err)
return
}
console.log (' Listening at http://localhost:8888 ')
})

Then we modify the Webpack.config.js configuration file

① change Config.output.publicPath to '/':

Output configuration
: {
//output path is myproject/output/static
path:path.resolve (__dirname, ' ... /output/static '),
publicpath: '/',
filename: ' [name].[ Hash].js ',
chunkfilename: ' [id].[ Chunkhash].js '
},

② the filename in the htmlwebpackplugin in plugins as ' app/index/index.html '

Plugins: [
new Htmlwebpackplugin ({
filename: ' app/index/index.html '),
template:path.resolve (__ DirName, '. /app/index/index.html '),
inject:true
})
]

At this point, we run the following command in the project root directory to open the service:

Node Build/dev-server.js

Enter http://localhost:8888/app/index/index.html in the browser, and if it succeeds, it will be the same as the result of running output->static->index.html on the previous local file.

Don't believe it?

In order not to modify Webpack.config.js, create a new Webpack.dev.conf.js file in the build directory, meaning the configuration file to read in development mode and write the contents:

var htmlwebpackplugin = require (' html-webpack-plugin ')
var path = require (' path ');
Introduction of basic configuration
var config = require ('./webpack.config ');
Config.output.publicPath = '/';
Config.plugins = [
new Htmlwebpackplugin ({
filename: ' app/index/index.html '),
template:path.resolve (__ DirName, '. /app/index/index.html '),
inject:true
})
];
module.exports = config;

This allows the configuration file in the dev environment to overwrite the basic configuration file, only in Dev-server.js

var config = require ('./webpack.config ')

To

var config = require ('./webpack.dev.conf ')

Here, we have used webpack-dev-middleware to build a basic development environment, but each time we modify the code, we still need to manually refresh the browser, then introduce Gegacay (so-called thermal loading, meaning that we can track the changes in our code, and automatically update the interface, It can even preserve the state of the program. ), we need to webpack-hot-middleware the middleware to complete the thermal loading.

In conjunction with Webpack-dev-middleware use, we also need to do is:

The first step: install (we have already installed above)

NPM Install Webpack-dev-middleware--save-dev

Step Two: Add three plug-ins to the Webpack.dev.conf.js configuration file as follows:

var htmlwebpackplugin = require (' html-webpack-plugin ')
var path = require (' path ');
var webpack = require (' Webpack ');
Introduction of basic configuration
var config = require ('./webpack.config ');
Config.output.publicPath = '/';
Config.plugins = [
//Add three plugins
new Webpack.optimize.OccurenceOrderPlugin (),
new Webpack. Hotmodulereplacementplugin (),
new Webpack. Noerrorsplugin (),
new Htmlwebpackplugin ({
filename: ' app/index/index.html ',
template:path.resolve (__dirname, '.. /app/index/index.html '),
inject:true
})
];
module.exports = config;

Step three: Add ' webpack-hot-middleware/client ' to the Portal configuration in the Webpack.config.js file as follows:

Entry: [' Webpack-hot-middleware/client ', Path.resolve (__dirname, '. /app/index/index.js ')],

Step Fourth: Use Plug-ins in dev-server.js files

Introducing the necessary modules
var Express = require (' Express ')
var webpack = require (' Webpack ')
var config = require ('./webpack . dev.conf ')
///Create a Express instance
var app = Express ()
//Call Webpack and pass configuration past
var compiler = webpack (config)
//using Webpack-dev-middleware middleware
var devmiddleware = require (' Webpack-dev-middleware ') (compiler, {
PublicPath:config.output.publicPath,
stats: {
colors:true,
chunks:false
}
})
//Use Webpack-hot-middleware middleware
var hotmiddleware = require (' Webpack-hot-middleware ') (compiler)
//Register middleware
App.use (Devmiddleware)
//Register middleware
App.use (hotmiddleware)
//Monitor port 8888, turn on server
App.listen (8888, function (err) {
if (err) {
console.log (err)
return
}
console.log (' Listening at http:// localhost:8888 ')
})

Now restart the service and then modify the page color in Favlist.vue to ' black ':

<style> body
{
color:black;
}
</style>

A save can see the modified effect, do not need to manually refresh the browser la la ~\ (≧▽≦)/~ la La.

Just modified the Portal configuration in this basic profile of webpack.config.js, in order not to modify this basic configuration file, we need to change the configuration in the Webpack.dev.conf.js file:

var htmlwebpackplugin = require (' html-webpack-plugin ')
var path = require (' path ');
var webpack = require (' Webpack ');
Introduction of basic configuration
var config = require ('./webpack.config ');
Config.output.publicPath = '/';
Config.plugins = [
new Webpack.optimize.OccurenceOrderPlugin (),
new Webpack. Hotmodulereplacementplugin (),
new Webpack. Noerrorsplugin (),
new Htmlwebpackplugin ({
filename: ' app/index/index.html ',
template:path.resolve (__dirname, '.. /app/index/index.html '),
inject:true
})
];
Dynamically injecting webpack-hot-middleware/client
var devclient = ' webpack-hot-middleware/client ' into the Portal configuration;
Object.keys (config.entry). ForEach (function (name, i) {
var extras = [Devclient]
config.entry[name] = Extras.concat (Config.entry[name])
})
module.exports = config;

Then modify the Portal configuration in the Webpack.config.js file to the following configuration:

Entry: {
index: [
path.resolve (__dirname, ' ... /app/index/index.js ')
]
},

Restart the service, modify the background color in the Favlist.vue, view the browser again, and find that it can be hot loaded. Here is not finished, here is only to hear the Favlist.vue file changes, in order to be able to monitor the index.html file changes, we still need to do some work.

First step: In the Dev-server.js file to monitor the HTML file change event, the modified Dev-server.js file is as follows:

Introducing the necessary modules
var Express = require (' Express ')
var webpack = require (' Webpack ')
var config = require ('./webpack . dev.conf ')
///Create a Express instance
var app = Express ()
//Call Webpack and pass configuration past
var compiler = webpack (config)
//using Webpack-dev-middleware middleware
var devmiddleware = require (' Webpack-dev-middleware ') (compiler, {
PublicPath:config.output.publicPath,
stats: {
colors:true,
chunks:false
}
})
var Hotmiddleware = require (' Webpack-hot-middleware ') (compiler)
//Webpack plugin, listening for HTML file changes event
Compiler.plugin (' Compilation ', function (compilation) {
compilation.plugin (' Html-webpack-plugin-after-emit ', function (data, CB) {
//Post event
Hotmiddleware.publish ({action: ' reload '})
CB ()
})
//Register middleware
App.use (Devmiddleware)
//Register middleware
App.use (hotmiddleware)
//Monitor port 8888, turn on server
App.listen (8888, function (err) {
if (err) {
console.log (err)
return
}
console.log (' Listening at http:// localhost:8888 ')
})

Step Two: Modify the Webpack.dev.conf.js file

var htmlwebpackplugin = require (' html-webpack-plugin ')
var path = require (' path ');
var webpack = require (' Webpack ');
Introduction of basic configuration
var config = require ('./webpack.config ');
Config.output.publicPath = '/';
Config.plugins = [
new Webpack.optimize.OccurenceOrderPlugin (),
new Webpack. Hotmodulereplacementplugin (),
new Webpack. Noerrorsplugin (),
new Htmlwebpackplugin ({
filename: ' app/index/index.html ',
template:path.resolve (__dirname, '.. /app/index/index.html '),
inject:true
})
];
Dynamically inject webpack-hot-middleware/client
//var devclient = ' webpack-hot-middleware/client ' into the Portal configuration;
var devclient = './build/dev-client ';
Object.keys (config.entry). ForEach (function (name, i) {
var extras = [Devclient]
config.entry[name] = Extras.concat (Config.entry[name])
})
module.exports = config;

The devclient variable is modified in the file, and the ' webpack-hot-middleware/client ' is replaced with './build/dev-client ', which will eventually result in our portal configuration becoming the following:

Entry: {
index: [
'./build/dev-client ',
path.resolve (__dirname, ' ... /app/index/index.js ')
]
},

Step three: Create a new Build/dev-client.js file and edit the following:

var hotclient = require (' webpack-hot-middleware/client ')
//Subscribe to event, perform page refresh
when event.action = = = ' Reload ' Hotclient.subscribe (function (event) {
if (event.action = = ' Reload ') {
window.location.reload ()
}
})

Here we subscribe to an event in addition to the ' Webpack-hot-middleware/client ', which is triggered when event.action = = ' Reload ', and there are events published in Dev-server.js:

Webpack plugin, listening for HTML file changes event
Compiler.plugin (' compilation ', Function (compilation) {
Compilation.plugin (' Html-webpack-plugin-after-emit ', function (data, CB) {
//Publish event
Hotmiddleware.publish ({action: ' Reload '}) C18/>CB ()
})
})

In this way, when our HTML file changes, we can listen to, and eventually perform the page refresh, without requiring us to manually refresh. Look at the effect:

At this point, the development environment finally finished.

The above is a small set to introduce the vue2.0+webpack environment of the construction process, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.