一、初始化項目
首先,進入到項目目錄
然后用npm初始化項目
npm init
package name: (todo) todolist
version: (1.0.0)
description: demo
git repository:
keywords:
author: doctor
license: (ISC)
然后會讓輸入一些信息,這里我只寫了文件名和作者
然后會打出第一段配置
{
"name": "todolist",
"version": "1.0.0",
"description": "demo",
"main": "vue.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "doctor",
"license": "ISC",
"dependencies": {
"vue": "^2.5.13",
"webpack": "^3.11.0",
"vue-loader": "^14.1.1",
"css-loader": "^0.28.9",
"vue-template-compiler": "^2.5.13"
},
"devDependencies": {}
}
Is this ok? (yes)
我們輸入yes 點回車就OK了
目錄下就生成了一個package.json文件
內(nèi)容就是我們輸出的那些
二、安裝webpack和vue
一開始我們安裝3個資源
1.webpack
2.vue
3.vue-loader
npm install webpack vue vue-loader (全局安裝了webpack可省掉webpack)
等待安裝完成
我們發(fā)現(xiàn)目錄里面多了一些東西

我們的package.json也多了一些內(nèi)容
就是dependencies。我們項目的依賴
"dependencies": {
"vue": "^2.5.13",
"vue-loader": "^14.1.1",
"webpack": "^4.0.0"
}
另外,控制臺還輸出可一些東西
npm WARN vue-loader@14.1.1 requires a peer of css-loader@* but none is installed. You must install peer dependencies yourself.
npm WARN vue-loader@14.1.1 requires a peer of vue-template-compiler@^2.0.0 but none is installed. You must install peer dependencies yourself.
我們少了兩個依賴 css-loader,vue-template-compiler
于是我們需要繼續(xù)下載
npm install css-loader vue-template-compiler
報錯權限不夠,請用管理員再次運行該命令
于是我直接又運行了一次,OK了
三、訪問vue文件
1.在目錄下建一個src,再在src下新建一個app.vue
在app.vue里面簡單的寫一些內(nèi)容
<template>
<div id="test">{{text}}</div>
</template>
<script>
export default {
data(){
return {
text:'hello webpack!'
}
}
}
</script>
<style>
#text{
color: #999;
}
</style>
但是網(wǎng)頁是無法識別 .vue后綴的文件的
都是打包之后才能訪問的
我們繼續(xù)在src下新建一個 index.js文件
通過index.js來加載app.vue里面的內(nèi)容
import Vue from 'vue'
import App from './app.vue'
//申明一個空div
const root=document.createElement('div');
document.body.appendChild(root);
//把app.vue的內(nèi)容掛載到空div上
new Vue({
render:(h) =>h(App)
}).$mount(root);
在更目錄下新建一個 webpack.config.js
const path=require('path')
module.exports={
//配置入口
entry:path.join(__dirname,'src/index.js'),
output:{//配置打包出口文件
filename:'bundle.js',
path:path.join(__dirname,'dist')
},
module:{
rules:[
{//讓webpack識別vue模板
test:/.vue$/,
loader:'vue-loader'
}
]
}
}
這個配置并沒有使用,也就是說還沒被引用
我們要去package.json把webpack.config.js引用進去
在script下面的test后面加入一行 build
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build":"webpack --config webpack.config.js"
}
然后在控制臺輸入
npm run build 就會生成一個dist目錄,在里面有一個bundlle.js


剛剛被坑了,全局下載了webpack,環(huán)境里面裝了個局部的webpack
導致npm run build 報錯
而且全局的webpack是3.11版本,局部下載的居然是4.0.0