1.首先新建一个目录vue-wkdemo,这是我们的项目目录。执行 npm init 命令生成package.json文件。执行npm init之后,会提示你填写一些项目的信息,一直回车默认就好了,或者直接执行 npm init -y 直接跳过询问步骤。
2.安装项目依赖项
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 html-webpack-plugin --save-dev
3.新建入口文件index.js,文件位置放置为:vue-wkdemo->app->index->index.js
import Vue from 'Vue' import Favlist from './components/Favlist.vue' Vue.config.debug = true;//开启错误提示 window.onload = function () { new Vue({ el: '#app', components: { 'my-component': Favlist } }); }
4.构建index.html模版,文件位置放置为:vue-wkdemo->app->index->index.html
<!DOCTYPE html> <html lang="zh"> <head> <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, user-scalable=no"> <meta charset="utf-8"> <title>首页</title> </head> <body> <div id="app"> <my-component></my-component> </div> </body> </html>
5.构建vue组件Favlist.vue ,文件放置为:vue-wkdemo->app->index->components->Favlist.vue
<template id="template-home"> <div> <div v-for="n in 10">div</div> </div> </template> <style> body { color: red; } </style>
6.构建 webpack.config.js ,文件放置为:vue-wkdemo->build->webpack.config.js
// nodejs 中的path模块 var path = require('path'); var HtmlWebpackPlugin = require('html-webpack-plugin') module.exports = { // 入口文件,path.resolve()方法,可以结合我们给定的两个参数最后生成绝对路径,最终指向的就是我们的index.js文件 entry: path.resolve(__dirname, '../app/index/index.js'), // 输出配置 output: { // 输出路径是 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: [ // 使用vue-loader 加载 .vue 结尾的文件 { test: /.vue$/, 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.运行构建命令 :
webpack --display-modules --display-chunks --config build/webpack.config.js