環境介紹css
系統:macOSHigh Sierra 10.13
node版本:v8.4.0
npm版本:5.3.0html
搭建過程vue
npm init
,輸入必要的信息npm install webpack --save-dev
(注:可採用淘寶源,能夠安裝一個nrm工具,這個工具可用於切換npm包的獲取地址,具體非本文主要內容)npm install --save-dev path
安裝path以備使用在項目目錄下新建一個文件,webpack.config.js
,內容代碼以下,官網直接拿過來的node
var path = require('path'); module.exports = { entry: './app/index.js', output: { filename: 'index.js', path: path.resolve(__dirname, 'dist') } };
有了上面這些,按照官網就能夠來進行編譯了,具體請查看官網,那麼如何來進行vue項目的構建呢,請繼續往下看。webpack
*.vue
文件,咱們還須要vue-template-compiler
,還須要vue-loader
來加載vue安裝完成以後,新建目錄結構如圖
git
其中,代碼以下Examples.vue
github
<template> <p>Hello,{{name}}</p> </template> <script> export default { name: 'Examples', data: function() { return { name: 'jackwang' } } }; </script>
index.js
web
import Vue from 'vue'; import Examples from './template/Examples.vue'; new Vue({ el: '#app', components: { 'Examples': Examples } });
index.html
npm
<body id="app"> <examples></examples> <script src="../dist/index.js"></script> </body>
而後進行項目[請見github示例]編譯,打開瀏覽器,發現控制檯,報了以下錯誤json
[Vue warn]: You are using the runtime-only build of Vue where the
template compiler is not available. Either pre-compile the templates
into render functions, or use the compiler-included build.(found in <Root>)
看npm包中的vue的package.json
能夠知道,main的指向dist/vue.runtime.common.js
爲了解決這個問題,只要咱們在webpack.config.js
中加上這個便可
resolve: { alias: { vue: 'vue/dist/vue.js' // 注意此處爲坑 } }
此時在再加載頁面發現
[Vue warn]: Do not mount Vue to <html> or <body> - mount to normal
elements instead.
實際上是vue不容許在body上操做,於是我將id="app"放到了div上,此時一個vue項目基本搭建完成
有些朋友可能很喜歡css in js
,當你寫某些組件時,將css放在組件當中,它的可移植性很是高,示例以下,在Examples.vue
中添加
<style> p{color: red;} </style>
可是僅僅這樣沒法進行成功編譯的,咱們還須要loader來對這些樣式進行編譯,咱們須要style-loader將style標籤注入到頁面當中,同時須要css-loader
來加提取css,npm install --save-dev style-loader
並在webpack.config.js
中module
中rules
添加規則,css-loader同理,(注:use中是從右到左執行)
{test: /\.css/, use: 'style-loader!css-loader'}
此時再編譯便可,爲了便於使用,能夠再package.json
中添加build命令,則能夠用npm run build
來進行編譯,以下,將build寫在這個位置
"scripts": { "build": "webpack --watch", // 就是這句,這樣能夠熱更新 "test": "echo \"Error: no test specified\" && exit 1" //這句是默認的,不用管 }
12.看起來是完了,是若是要引入一張背景圖片呢,看看會出現什麼問題,發現編譯不經過,因此須要url-loader
來進行url解析,同理10的安裝方法,效果再一次實現
結語
若是再遇到什麼報錯,請看是否是還須要什麼loader,利用webpack搭建vue基本就說到這了,示例地址:https://github.com/IhInspirat...,寫的若有錯誤或不完整之處,請評論交流,謝謝 !