各個社區已經有無數篇帖子介紹如何使用webpack搭建前端項目,但不管是出於學習webpack的目的仍是爲了解決工做實際須要都面臨着一個現實問題,那就是版本更新。別人的帖子可能剛寫好版本就更新了,又要對着帖子找文檔。css
但這個過程十分重要,由於你想要的一切早已都在文檔中給出了說明,在查閱文檔的過程當中不但能學會正確的使用工具更加強了閱讀文檔這種姿式正確的學習能力。html
本文就是記錄一次不斷遭遇版本問題,一路查閱文檔達到學習目的的經歷,分享給你們。文章中每一個章節提到的相關文檔都會在本章節總結,在文章最後我還會將全部相關文檔的連接進行彙總出來方便你們學習。前端
第一個要查閱的就是webpack的官方文檔,因爲webpack近年來的使用普遍,中文文檔早已跟上。vue
webpack官方文檔: https://webpack.docschina.org/
咱們能夠在文檔-指南中找到安裝相關的內容。node
webpack安裝: https://webpack.docschina.org...
官方已說明不推薦全局安裝webpack由於這樣會將你項目中的webpack鎖定到指定版本。不須要全局安裝的可跳過此步驟webpack
es6
npm i -g webpack<h2>1. 項目初始化</h2> <h3>初始化項目</h3> <p>在項目目錄下初始化項目會獲得package.json文件:</p> <pre><code class="coffeescript">npm init
安裝webpack和webpack-dev-server以及Vue
webpack4會依賴webpack-cli,若是你沒有安裝也沒必要擔憂,npm會直接報錯提示你web
webpack安裝: https://webpack.docschina.org...
webpack-dev-server: https://webpack.docschina.org...<h2>1. 項目初始化</h2> <h3>初始化項目</h3> <p>在項目目錄下初始化項目會獲得package.json文件:</p> <pre><code class="coffeescript">npm initnpm i webpack webpack-dev-server webpack-cli --save-dev
npm i webpack webpack-dev-server webpack-cli --save-dev
vue-router
npm i vue --save
<h3>配置webpack.config.js</h3> <p>根目錄下新建webpack的配置文件webpack.config.js。<br>配置 入口、出口路徑、打包後文件名和devServer的相關配置項</p> <blockquote>使用一個webpack的配置文件:<a href="https://webpack.docschina.org/guides/getting-started/#%E4%BD%BF%E7%94%A8%E4%B8%80%E4%B8%AA%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6" rel="nofollow noreferrer">https://webpack.docschina.org...</a> </blockquote>
var path = require('path');
var webpack = require('webpack');vuexmodule.exports = {
//項目入口文件
entry: './src/main.js',
output: {
//打包出口路徑
path: path.resolve(__dirname, './dist'),
//經過devServer訪問路徑
publicPath: '/dist/',
//打包後的文件名
filename: 'main.js'
},
mode:'development',
devServer: {
historyApiFallback: true,
overlay: true
}
};```
根目錄下新建index.html(模板以下)
新建index.html做爲項目的主體頁面,留出入口文件,入口文件的路徑爲webpack打包後輸出的路徑。
```<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>webpack-vue</title>
<meta name="description" content="">
<meta name="keywords" content="">
</head>
<body>
<script src="/dist/main.js"></script>
</body>
</html><h3>新建入口文件</h3> <p>新建在src目錄用來存放各類組件和靜態文件,在src目錄下新建入口文件main.js</p> <h2>2. webpack的準備工做</h2> <p>爲方便開發調試,打包以及後期的代碼編寫便捷,咱們須要對webpack進行初步配置</p> <h3>自定義npm命令</h3> <p>package.json 增長 scripts:</p>
"scripts": {
"dev": "webpack-dev-server --hot --open",
"build": "webpack --mode production --progress --hide-modules"
},<p>這一步的目的是簡化在命令行中輸入複雜指令的操做,如需執行上述兩命令只須要在命令行執行:</p> <pre><code class="coffeescript">npm run dev npm run build
webpack-dev-server --hot --open
目的是開啓一個本地服務,--hot
爲熱加載,可實視查看頁面狀態,--open
直接從瀏覽器打開webpack --mode production --progress --hide-modules
是打包整個項目的指令,--mode production
是以生產模式打包,這樣會獲得體積更小的文件,有興趣的同窗能夠試試不加這個指令,看看差距到底有多大。--progress
打印出編譯進度的百分比值,hide-modules
隱藏關於模塊的信息
webpack的全部命令行能夠在 api-命令行接口(cli) 中找到webpack命令行接口: https://webpack.docschina.org...配置webpack解析(resolve)
webpack.config.js中增長:
resolve: { //路徑別名 alias: { 'vue$': 'vue/dist/vue.esm.js', '@':path.resolve(__dirname, './src'), }, //路徑別名自動解析肯定的擴展 tensions: ['.js', '.vue', '.json'] },
resolve
是webpack關於解析的配置項,alias
容許你在項目中使用路徑別名代替複雜的路徑。extensions
會讓webpack自動查找特定後綴的文件,在項目中引入文件時將沒必要再書寫文件後綴。
至於爲什麼將vue的路徑別名指向vue/dist/vue.esm.js
請看下一章節vue的內容。webpack解析(resolve): https://webpack.docschina.org...3. 引入Vue
這一步咱們先暫不考慮使用Vue的單頁面組件。
經過查看 node_modules/vue/dist/README.md 咱們能夠獲得關於webpack配置的說明,引入vue其實是引用 node_modules/vue/dist/vue.esm.js,有理有據安心使用,而且會告訴你若是你在使用webpack 1.0應該引用vue.common.js,這即是上一步配置路徑別名的依據。
在index.html中添加掛載點dom(#app)
```<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>webpack-vue</title>
<meta name="description" content="">
<meta name="keywords" content="">
</head>
<body>
<div id="app">{{message}}</div>
<script src="/dist/main.js"></script>
</body>
</html><h3>在main.js中引入vue</h3>
import Vue from 'vue'
var app = new Vue({
el: "#app",
data: {
message: 'hello webpack!!'
}
})<p>啓動server,能夠預覽到頁面顯示 'hello webpack!!'。</p> <pre><code class="coffeescript">npm run dev
4. 配置loader——使用 css/scss
webpack默認只能解析js文件,所以須要在webpack.config.js中配置相應的解析器。
安裝scss和相應樣式文件解析器
npm i node-sass css-loader vue-style-loader sass-loader –save-dev
<p>關於webpack解析樣式的文檔比較散亂,經過粗略查閱,<br><code>css-loader</code>用來解析css文件,<br><code>style-loader</code>用來解析dom中經過<code><style></style></code>注入的樣式,<br>而<code>vue-style-loader</code>是vue官方基於style-loader開發的適用於vue的樣式解析,<br><code>sass-loader</code>用來解析sass/scss文件</p> <blockquote>webpack - loader:<a href="https://webpack.docschina.org/loaders/" rel="nofollow noreferrer">https://webpack.docschina.org...</a><br>vue-style-loader:<a href="https://www.npmjs.com/package/vue-style-loader" rel="nofollow noreferrer">https://www.npmjs.com/package...</a> </blockquote> <h3>在webpack.config.js中配置解析器</h3>
module: {
rules: [{
test: /.css$/,
use: [
'vue-style-loader',
'css-loader'
]
},{
test: /.scss$/,
use: [
'vue-style-loader',
'css-loader',
'sass-loader'
]
},
{
test: /.sass$/,
use: [
'vue-style-loader',
'css-loader',
'sass-loader?indentedSyntax'
]
}]
},<p>以上配置意爲:<br><code>.css</code>爲後綴的文件使用<code>css-loader</code>, <code>vue-style-loader</code>解析<br><code>.scss</code>和<code>.sass</code>爲後綴的文件使用<code>sass-loader</code>,<code>css-loader</code>, <code>vue-style-loader</code>解析<br>解析順序是由下到上的</p> <blockquote>webpack - module:<a href="https://webpack.docschina.org/configuration/module/#module-rules" rel="nofollow noreferrer">https://webpack.docschina.org...</a><br>webpack - sass-loader:<a href="https://webpack.docschina.org/loaders/sass-loader/" rel="nofollow noreferrer">https://webpack.docschina.org...</a> </blockquote> <h3>在項目中使用、引入樣式(測試)</h3> <p>在src目錄下新建目錄assets/styles存放統同樣式,新建index.scss,寫一段scss代碼:</p> <pre><code class="scss">$appColor:red; #app{ color:$appColor; }
在main.js中引入樣式:
import ‘./assets/styles/index.scss’
再次重啓服務能夠看到樣式已經加載成功了
5. 配置loader——使用圖片
一樣webpack人沒法解析圖片格式的文件,須要把圖片當作模塊使用file-loader解析。
file-loader: https://webpack.docschina.org...安裝file-loader
npm i file-loader --save-dev
<h3>在webpack.config.js中配置解析器</h3>
{
test: /.(png|jpg|gif|svg)$/,
loader: 'file-loader',
options: {
name: '[name].[ext]?[hash]'
}
}<h3>在項目中引入圖片(測試)</h3> <p>在src目錄下按照代碼中路徑準備一張圖片</p>
Vue.component('myComponent', {
template: '<img :src="url" />',
data() {
return {
url: require('./assets/images/logo.png')
}
}
})```
在index.html中使用該組件
```<div id="app">
{{message}}
<my-component></my-component>
</div><p>重啓服務,圖片應該被成功加載了。</p> <h2>6. 配置loader——使用babel</h2> <p>babel可讓咱們在項目中自由的使用es6語法,他會爲咱們將es6語法編譯成瀏覽器廣泛通用的es5語法。<br>在此以前咱們必需要對babel有必定的瞭解:</p> <blockquote>babel官方文檔:<a href="https://babel.docschina.org/docs/en/usage" rel="nofollow noreferrer">https://babel.docschina.org/d...</a> </blockquote> <p>在babel的使用指南中咱們看到安裝babel須要安裝的依賴和配置babel的方法。<br>而且咱們得知一個噩耗,babel從7.0開始與以前版本有寫不兼容了。若是你的package.json中babel的版本混亂,很容易形成配置失敗。</p> <h3>安裝babel</h3> <pre><code class="coffeescript">npm install --save-dev @babel/core @babel/cli @babel/preset-env npm install --save @babel/polyfill
注意:
- 其中preset是babel的配置,babel-loader在webpack中解析babel中會用到,polyfill也是babel的一個依賴
- babel的6.0 和7.0不兼容,若是package.json中版本混亂建議降級活升級以統一版本
在webpack.config.js中配置解析器
babel的webpack配置: https://babel.docschina.org/s... 選擇webpackmodule增長一條rules:
{ test: /\.js$/, exclude: /node_modules/, loader: "babel-loader" }
入口文件更改成:
entry: ["@babel/polyfill", './src/main.js'],
新建配置文件.babelrc
注意查看關於env的配置文檔,新版本寫法有變化。
@babel/preset-env: https://babel.docschina.org/d...{ "presets": [ [ "@babel/preset-env", { "useBuiltIns": "entry" } ] ] }
檢測es6語法(正常運行說明babel配置成功)
在src下新建util.js
export default function getData() { return new Promise((resolve, reject) => { resolve('ok'); }) }
main.js
//引入組件 import getData from './util'; var app = new Vue({ el: "#app", data: { message: 'hello webpack!!' }, methods: { async fetchData() { const data = await getData(); this.message = data; } }, created() { this.fetchData(); } })
import getData from './util';
常見報錯
Can't resolve 'babel-polyfill' in 'E:\vue\webpack-vue'
webpack的入口文件polyfill版本與配置寫法不匹配
錯誤:entry: ["babel-polyfill", './src/main.js'],
正確:entry: ["@babel/polyfill", './src/main.js'],regeneratorRuntime is not defined
未安裝@babel/polyfill
npm i babel-polyfill –savePlugin/Preset files are not allowed to export objects
webpack的報錯,版本混亂,不兼容
清理package.json中的babel依賴,刪除node_module,從新執行npm install,再次安裝babel依賴時注意版本統一7. 使用Vue單文件組件
vue-loader中介紹瞭如何使用Vue單文件組件:
vue-loader: https://vue-loader.vuejs.org/zh/安裝vue-loader及依賴
npm i vue-loader vue-template-compiler –save-dev
<h3>配置webpack.config.js</h3> <blockquote>Vue單文件組件:<a href="https://vue-loader.vuejs.org/zh/guide/" rel="nofollow noreferrer">https://vue-loader.vuejs.org/...</a> </blockquote>
// webpack.config.js
const VueLoaderPlugin = require('vue-loader/lib/plugin')module.exports = {
module: {
rules: [
// ... 其它規則
{
test: /.vue$/,
loader: 'vue-loader'
}
]
},
plugins: [
// 請確保引入這個插件!
new VueLoaderPlugin()
]
}
```準備單文件組件
在src目錄下建立文件App.vue
在src目錄下新建目錄components用來存放單文件組件,新建文件header.vueApp.vue
<div> <home-header user="vict"></home-header> </div> </template> <script> import homeHeader from '@/components/header.vue' export default { name:'app', components:{ homeHeader } } </script> <style lang="scss" scoped> $txtColor:red; .sg{ color:$txtColor } </style>
header.vue(子組件)
<template> <div> header <span>color</span> <img src="@/assets/images/logo.png"> {{this.message}} - {{this.user}} </div> </template> <script> export default { name:'homeHeader', data () { return { message:'hello world' } }, props: { user:String } } </script> <style lang="scss" scoped> span{ color:green } </style>
main.js
import Vue from 'vue' import App from './App.vue' import './assets/styles/index.scss' new Vue({ render:h => h(App) }).$mount('#app')
8. 解決靜態文件
在.vue中url路徑將被解析成webpack模塊請求,
這裏建議在webpack.config.js中配置路徑別名以方便在單文件組件中引用圖片等靜態資源
在單文件組件中能夠這樣使用:
<img src="@/assets/images/logo.png">
9. 注入Vue Router
vue-router: https://router.vuejs.org/zh/安裝VueRouter
npm i vue-router –save
<h3>在main.js的Vue實例中注入Router</h3>
import Vue from 'vue'
import App from './App'
//引入router組件
import router from './router/router'
import './assets/styles/reset.css'new Vue({
//注入router
router,
render:h => h(App)
}).$mount('#app')<h3>構建router組件</h3> <p>按照路徑建立router文件:src/router/router.js</p> <p>router.js</p>
import Vue from 'vue'
import VueRouter from 'vue-router'import Page1 from '@/components/page1'
import Page2 from '@/components/page2'Vue.use(VueRouter)
export default new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes: [{
path: '/',
name:'home',
component: Page1
},{
path: '/page2',
name:'page2',
component: Page2
}]
})<p><em>常見的渲染失敗的緣由:</em></p> <ul> <li><em>router實例的路由配置項 routes,不要誤寫成 routers</em></li> <li><em>routes配置項中必需要有路徑爲’/’,不然渲染失敗</em></li> </ul> <h3>使用router</h3> <p>在App.vue中能夠直接使用<code><router-view></code>和<code><router-link></code>標籤</p> <h2>10. 注入Vuex</h2> <blockquote>vuex: <a href="https://vuex.vuejs.org/zh/guide/" rel="nofollow noreferrer">https://vuex.vuejs.org/zh/guide/</a> </blockquote> <h3>安裝vuex</h3> <pre><code class="coffeescript">npm i vuex –save
在main.js的Vue實例中注入store
import Vue from 'vue' import App from './App' import router from './router/router' import store from './store/store' import './assets/styles/reset.css' new Vue({ router, store, render:h => h(App) }).$mount('#app')
構建store目錄
src/store/store.js
可按須要將state、actions、mutations拆分出來store.js
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ state: { cur:'OFF', }, actions: { changeCur (ctx,cur) { ctx.commit('changeCueMutations',cur) } }, mutations: { changeCueMutations (state,cur) { cur == 'OFF' ? state.cur = 'ON' :state.cur = 'OFF' } } })
11. 打包發佈
webpack.config.js中若是配置項:mode:'development', build的結果是未通過壓縮的很是的大
修改 package.json 中的scripts,將打包時的mode切換成production"scripts": { "test": "echo \"Error: no test specified\" && exit 1", "dev": "webpack-dev-server --hot --open", "build": "webpack --mode production --progress --hide-modules" },
文檔彙總
webpack相關
webpack官方文檔: https://webpack.docschina.org/
webpack安裝: https://webpack.docschina.org...
webpack-dev-server: https://webpack.docschina.org...
webpack配置: https://webpack.docschina.org...
webpack命令行接口: https://webpack.docschina.org...
webpack解析(resolve): https://webpack.docschina.org...
webpack - loader: https://webpack.docschina.org...
webpack - module: https://webpack.docschina.org...Vue相關
Vue官方文檔(中文): https://cn.vuejs.org/
Vue-cli: https://cli.vuejs.org/zh/guide/
Vue-router: https://router.vuejs.org/
Vuex: https://vuex.vuejs.org/
Vue-loader(單文件組件): https://vue-loader.vuejs.org/babel相關
babel官方文檔: https://babel.docschina.org/
babel使用指南: https://babel.docschina.org/d...
babel的配置: https://babel.docschina.org/s...
babel-env: https://babel.docschina.org/d...其餘
npm官方: https://www.npmjs.com/
npm CLI(命令行指令): https://docs.npmjs.com/
vue-style-loader: https://www.npmjs.com/package...
node-sass: https://www.npmjs.com/search?...
npm i vue --save<h3>配置webpack.config.js</h3> <p>根目錄下新建webpack的配置文件webpack.config.js。<br>配置 入口、出口路徑、打包後文件名和devServer的相關配置項</p> <blockquote>使用一個webpack的配置文件:<a href="https://webpack.docschina.org/guides/getting-started/#%E4%BD%BF%E7%94%A8%E4%B8%80%E4%B8%AA%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6" rel="nofollow noreferrer">https://webpack.docschina.org...</a> </blockquote>
var path = require('path');
var webpack = require('webpack');vuexmodule.exports = {
//項目入口文件
entry: './src/main.js',
output: {
//打包出口路徑
path: path.resolve(__dirname, './dist'),
//經過devServer訪問路徑
publicPath: '/dist/',
//打包後的文件名
filename: 'main.js'
},
mode:'development',
devServer: {
historyApiFallback: true,
overlay: true
}
};```
根目錄下新建index.html(模板以下)
新建index.html做爲項目的主體頁面,留出入口文件,入口文件的路徑爲webpack打包後輸出的路徑。
```<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>webpack-vue</title>
<meta name="description" content="">
<meta name="keywords" content="">
</head>
<body>
<script src="/dist/main.js"></script>
</body>
</html><h3>新建入口文件</h3> <p>新建在src目錄用來存放各類組件和靜態文件,在src目錄下新建入口文件main.js</p> <h2>2. webpack的準備工做</h2> <p>爲方便開發調試,打包以及後期的代碼編寫便捷,咱們須要對webpack進行初步配置</p> <h3>自定義npm命令</h3> <p>package.json 增長 scripts:</p>
"scripts": {
"dev": "webpack-dev-server --hot --open",
"build": "webpack --mode production --progress --hide-modules"
},<p>這一步的目的是簡化在命令行中輸入複雜指令的操做,如需執行上述兩命令只須要在命令行執行:</p> <pre><code class="coffeescript">npm run dev npm run build
webpack-dev-server --hot --open
目的是開啓一個本地服務,--hot
爲熱加載,可實視查看頁面狀態,--open
直接從瀏覽器打開webpack --mode production --progress --hide-modules
是打包整個項目的指令,--mode production
是以生產模式打包,這樣會獲得體積更小的文件,有興趣的同窗能夠試試不加這個指令,看看差距到底有多大。--progress
打印出編譯進度的百分比值,hide-modules
隱藏關於模塊的信息
webpack的全部命令行能夠在 api-命令行接口(cli) 中找到webpack命令行接口: https://webpack.docschina.org...配置webpack解析(resolve)
webpack.config.js中增長:
resolve: { //路徑別名 alias: { 'vue$': 'vue/dist/vue.esm.js', '@':path.resolve(__dirname, './src'), }, //路徑別名自動解析肯定的擴展 tensions: ['.js', '.vue', '.json'] },
resolve
是webpack關於解析的配置項,alias
容許你在項目中使用路徑別名代替複雜的路徑。extensions
會讓webpack自動查找特定後綴的文件,在項目中引入文件時將沒必要再書寫文件後綴。
至於爲什麼將vue的路徑別名指向vue/dist/vue.esm.js
請看下一章節vue的內容。webpack解析(resolve): https://webpack.docschina.org...3. 引入Vue
這一步咱們先暫不考慮使用Vue的單頁面組件。
經過查看 node_modules/vue/dist/README.md 咱們能夠獲得關於webpack配置的說明,引入vue其實是引用 node_modules/vue/dist/vue.esm.js,有理有據安心使用,而且會告訴你若是你在使用webpack 1.0應該引用vue.common.js,這即是上一步配置路徑別名的依據。
在index.html中添加掛載點dom(#app)
```<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>webpack-vue</title>
<meta name="description" content="">
<meta name="keywords" content="">
</head>
<body>
<div id="app">{{message}}</div>
<script src="/dist/main.js"></script>
</body>
</html><h3>在main.js中引入vue</h3>
import Vue from 'vue'
var app = new Vue({
el: "#app",
data: {
message: 'hello webpack!!'
}
})<p>啓動server,能夠預覽到頁面顯示 'hello webpack!!'。</p> <pre><code class="coffeescript">npm run dev
4. 配置loader——使用 css/scss
webpack默認只能解析js文件,所以須要在webpack.config.js中配置相應的解析器。
安裝scss和相應樣式文件解析器
<h3>配置webpack.config.js</h3> <p>根目錄下新建webpack的配置文件webpack.config.js。<br>配置 入口、出口路徑、打包後文件名和devServer的相關配置項</p> <blockquote>使用一個webpack的配置文件:<a href="https://webpack.docschina.org/guides/getting-started/#%E4%BD%BF%E7%94%A8%E4%B8%80%E4%B8%AA%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6" rel="nofollow noreferrer">https://webpack.docschina.org...</a> </blockquote><h3>新建入口文件</h3> <p>新建在src目錄用來存放各類組件和靜態文件,在src目錄下新建入口文件main.js</p> <h2>2. webpack的準備工做</h2> <p>爲方便開發調試,打包以及後期的代碼編寫便捷,咱們須要對webpack進行初步配置</p> <h3>自定義npm命令</h3> <p>package.json 增長 scripts:</p><p>這一步的目的是簡化在命令行中輸入複雜指令的操做,如需執行上述兩命令只須要在命令行執行:</p> <pre><code class="coffeescript">npm run dev npm run buildwebpack-dev-server --hot --open--hot--openwebpack --mode production --progress --hide-modules--mode production--progresshide-modulesresolve: { //路徑別名 alias: { 'vue$': 'vue/dist/vue.esm.js', '@':path.resolve(__dirname, './src'), }, //路徑別名自動解析肯定的擴展 tensions: ['.js', '.vue', '.json'] },resolvealiasextensionsvue/dist/vue.esm.js<h3>在main.js中引入vue</h3><p>啓動server,能夠預覽到頁面顯示 'hello webpack!!'。</p> <pre><code class="coffeescript">npm run devnpm i node-sass css-loader vue-style-loader sass-loader –save-dev
npm i node-sass css-loader vue-style-loader sass-loader –save-dev
<p>關於webpack解析樣式的文檔比較散亂,經過粗略查閱,<br><code>css-loader</code>用來解析css文件,<br><code>style-loader</code>用來解析dom中經過<code><style></style></code>注入的樣式,<br>而<code>vue-style-loader</code>是vue官方基於style-loader開發的適用於vue的樣式解析,<br><code>sass-loader</code>用來解析sass/scss文件</p> <blockquote>webpack - loader:<a href="https://webpack.docschina.org/loaders/" rel="nofollow noreferrer">https://webpack.docschina.org...</a><br>vue-style-loader:<a href="https://www.npmjs.com/package/vue-style-loader" rel="nofollow noreferrer">https://www.npmjs.com/package...</a> </blockquote> <h3>在webpack.config.js中配置解析器</h3>
module: {
rules: [{
test: /.css$/,
use: [
'vue-style-loader',
'css-loader'
]
},{
test: /.scss$/,
use: [
'vue-style-loader',
'css-loader',
'sass-loader'
]
},
{
test: /.sass$/,
use: [
'vue-style-loader',
'css-loader',
'sass-loader?indentedSyntax'
]
}]
},<p>以上配置意爲:<br><code>.css</code>爲後綴的文件使用<code>css-loader</code>, <code>vue-style-loader</code>解析<br><code>.scss</code>和<code>.sass</code>爲後綴的文件使用<code>sass-loader</code>,<code>css-loader</code>, <code>vue-style-loader</code>解析<br>解析順序是由下到上的</p> <blockquote>webpack - module:<a href="https://webpack.docschina.org/configuration/module/#module-rules" rel="nofollow noreferrer">https://webpack.docschina.org...</a><br>webpack - sass-loader:<a href="https://webpack.docschina.org/loaders/sass-loader/" rel="nofollow noreferrer">https://webpack.docschina.org...</a> </blockquote> <h3>在項目中使用、引入樣式(測試)</h3> <p>在src目錄下新建目錄assets/styles存放統同樣式,新建index.scss,寫一段scss代碼:</p> <pre><code class="scss">$appColor:red; #app{ color:$appColor; }
在main.js中引入樣式:
import ‘./assets/styles/index.scss’
再次重啓服務能夠看到樣式已經加載成功了
5. 配置loader——使用圖片
一樣webpack人沒法解析圖片格式的文件,須要把圖片當作模塊使用file-loader解析。
file-loader: https://webpack.docschina.org...安裝file-loader
npm i file-loader --save-dev
<h3>在webpack.config.js中配置解析器</h3>
{
test: /.(png|jpg|gif|svg)$/,
loader: 'file-loader',
options: {
name: '[name].[ext]?[hash]'
}
}<h3>在項目中引入圖片(測試)</h3> <p>在src目錄下按照代碼中路徑準備一張圖片</p>
Vue.component('myComponent', {
template: '<img :src="url" />',
data() {
return {
url: require('./assets/images/logo.png')
}
}
})```
在index.html中使用該組件
```<div id="app">
{{message}}
<my-component></my-component>
</div><p>重啓服務,圖片應該被成功加載了。</p> <h2>6. 配置loader——使用babel</h2> <p>babel可讓咱們在項目中自由的使用es6語法,他會爲咱們將es6語法編譯成瀏覽器廣泛通用的es5語法。<br>在此以前咱們必需要對babel有必定的瞭解:</p> <blockquote>babel官方文檔:<a href="https://babel.docschina.org/docs/en/usage" rel="nofollow noreferrer">https://babel.docschina.org/d...</a> </blockquote> <p>在babel的使用指南中咱們看到安裝babel須要安裝的依賴和配置babel的方法。<br>而且咱們得知一個噩耗,babel從7.0開始與以前版本有寫不兼容了。若是你的package.json中babel的版本混亂,很容易形成配置失敗。</p> <h3>安裝babel</h3> <pre><code class="coffeescript">npm install --save-dev @babel/core @babel/cli @babel/preset-env npm install --save @babel/polyfill
注意:
- 其中preset是babel的配置,babel-loader在webpack中解析babel中會用到,polyfill也是babel的一個依賴
- babel的6.0 和7.0不兼容,若是package.json中版本混亂建議降級活升級以統一版本
在webpack.config.js中配置解析器
babel的webpack配置: https://babel.docschina.org/s... 選擇webpackmodule增長一條rules:
{ test: /\.js$/, exclude: /node_modules/, loader: "babel-loader" }
入口文件更改成:
entry: ["@babel/polyfill", './src/main.js'],
新建配置文件.babelrc
注意查看關於env的配置文檔,新版本寫法有變化。
@babel/preset-env: https://babel.docschina.org/d...{ "presets": [ [ "@babel/preset-env", { "useBuiltIns": "entry" } ] ] }
檢測es6語法(正常運行說明babel配置成功)
在src下新建util.js
export default function getData() { return new Promise((resolve, reject) => { resolve('ok'); }) }
main.js
//引入組件 import getData from './util'; var app = new Vue({ el: "#app", data: { message: 'hello webpack!!' }, methods: { async fetchData() { const data = await getData(); this.message = data; } }, created() { this.fetchData(); } })
import getData from './util';
常見報錯
Can't resolve 'babel-polyfill' in 'E:\vue\webpack-vue'
webpack的入口文件polyfill版本與配置寫法不匹配
錯誤:entry: ["babel-polyfill", './src/main.js'],
正確:entry: ["@babel/polyfill", './src/main.js'],regeneratorRuntime is not defined
未安裝@babel/polyfill
npm i babel-polyfill –savePlugin/Preset files are not allowed to export objects
webpack的報錯,版本混亂,不兼容
清理package.json中的babel依賴,刪除node_module,從新執行npm install,再次安裝babel依賴時注意版本統一7. 使用Vue單文件組件
vue-loader中介紹瞭如何使用Vue單文件組件:
vue-loader: https://vue-loader.vuejs.org/zh/安裝vue-loader及依賴
npm i vue-loader vue-template-compiler –save-dev
<h3>配置webpack.config.js</h3> <blockquote>Vue單文件組件:<a href="https://vue-loader.vuejs.org/zh/guide/" rel="nofollow noreferrer">https://vue-loader.vuejs.org/...</a> </blockquote>
// webpack.config.js
const VueLoaderPlugin = require('vue-loader/lib/plugin')module.exports = {
module: {
rules: [
// ... 其它規則
{
test: /.vue$/,
loader: 'vue-loader'
}
]
},
plugins: [
// 請確保引入這個插件!
new VueLoaderPlugin()
]
}
```準備單文件組件
在src目錄下建立文件App.vue
在src目錄下新建目錄components用來存放單文件組件,新建文件header.vueApp.vue
<div> <home-header user="vict"></home-header> </div> </template> <script> import homeHeader from '@/components/header.vue' export default { name:'app', components:{ homeHeader } } </script> <style lang="scss" scoped> $txtColor:red; .sg{ color:$txtColor } </style>
header.vue(子組件)
<template> <div> header <span>color</span> <img src="@/assets/images/logo.png"> {{this.message}} - {{this.user}} </div> </template> <script> export default { name:'homeHeader', data () { return { message:'hello world' } }, props: { user:String } } </script> <style lang="scss" scoped> span{ color:green } </style>
main.js
import Vue from 'vue' import App from './App.vue' import './assets/styles/index.scss' new Vue({ render:h => h(App) }).$mount('#app')
8. 解決靜態文件
在.vue中url路徑將被解析成webpack模塊請求,
這裏建議在webpack.config.js中配置路徑別名以方便在單文件組件中引用圖片等靜態資源
在單文件組件中能夠這樣使用:
<img src="@/assets/images/logo.png">
9. 注入Vue Router
vue-router: https://router.vuejs.org/zh/安裝VueRouter
npm i vue-router –save
<h3>在main.js的Vue實例中注入Router</h3>
import Vue from 'vue'
import App from './App'
//引入router組件
import router from './router/router'
import './assets/styles/reset.css'new Vue({
//注入router
router,
render:h => h(App)
}).$mount('#app')<h3>構建router組件</h3> <p>按照路徑建立router文件:src/router/router.js</p> <p>router.js</p>
import Vue from 'vue'
import VueRouter from 'vue-router'import Page1 from '@/components/page1'
import Page2 from '@/components/page2'Vue.use(VueRouter)
export default new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes: [{
path: '/',
name:'home',
component: Page1
},{
path: '/page2',
name:'page2',
component: Page2
}]
})<p><em>常見的渲染失敗的緣由:</em></p> <ul> <li><em>router實例的路由配置項 routes,不要誤寫成 routers</em></li> <li><em>routes配置項中必需要有路徑爲’/’,不然渲染失敗</em></li> </ul> <h3>使用router</h3> <p>在App.vue中能夠直接使用<code><router-view></code>和<code><router-link></code>標籤</p> <h2>10. 注入Vuex</h2> <blockquote>vuex: <a href="https://vuex.vuejs.org/zh/guide/" rel="nofollow noreferrer">https://vuex.vuejs.org/zh/guide/</a> </blockquote> <h3>安裝vuex</h3> <pre><code class="coffeescript">npm i vuex –save
在main.js的Vue實例中注入store
import Vue from 'vue' import App from './App' import router from './router/router' import store from './store/store' import './assets/styles/reset.css' new Vue({ router, store, render:h => h(App) }).$mount('#app')
構建store目錄
src/store/store.js
可按須要將state、actions、mutations拆分出來store.js
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ state: { cur:'OFF', }, actions: { changeCur (ctx,cur) { ctx.commit('changeCueMutations',cur) } }, mutations: { changeCueMutations (state,cur) { cur == 'OFF' ? state.cur = 'ON' :state.cur = 'OFF' } } })
11. 打包發佈
webpack.config.js中若是配置項:mode:'development', build的結果是未通過壓縮的很是的大
修改 package.json 中的scripts,將打包時的mode切換成production"scripts": { "test": "echo \"Error: no test specified\" && exit 1", "dev": "webpack-dev-server --hot --open", "build": "webpack --mode production --progress --hide-modules" },
文檔彙總
webpack相關
webpack官方文檔: https://webpack.docschina.org/
webpack安裝: https://webpack.docschina.org...
webpack-dev-server: https://webpack.docschina.org...
webpack配置: https://webpack.docschina.org...
webpack命令行接口: https://webpack.docschina.org...
webpack解析(resolve): https://webpack.docschina.org...
webpack - loader: https://webpack.docschina.org...
webpack - module: https://webpack.docschina.org...Vue相關
Vue官方文檔(中文): https://cn.vuejs.org/
Vue-cli: https://cli.vuejs.org/zh/guide/
Vue-router: https://router.vuejs.org/
Vuex: https://vuex.vuejs.org/
Vue-loader(單文件組件): https://vue-loader.vuejs.org/babel相關
babel官方文檔: https://babel.docschina.org/
babel使用指南: https://babel.docschina.org/d...
babel的配置: https://babel.docschina.org/s...
babel-env: https://babel.docschina.org/d...其餘
npm官方: https://www.npmjs.com/
npm CLI(命令行指令): https://docs.npmjs.com/
vue-style-loader: https://www.npmjs.com/package...
node-sass: https://www.npmjs.com/search?...<p>關於webpack解析樣式的文檔比較散亂,經過粗略查閱,<br><code>css-loader</code>用來解析css文件,<br><code>style-loader</code>用來解析dom中經過<code><style></style></code>注入的樣式,<br>而<code>vue-style-loader</code>是vue官方基於style-loader開發的適用於vue的樣式解析,<br><code>sass-loader</code>用來解析sass/scss文件</p> <blockquote>webpack - loader:<a href="https://webpack.docschina.org/loaders/" rel="nofollow noreferrer">https://webpack.docschina.org...</a><br>vue-style-loader:<a href="https://www.npmjs.com/package/vue-style-loader" rel="nofollow noreferrer">https://www.npmjs.com/package...</a> </blockquote> <h3>在webpack.config.js中配置解析器</h3>
module: {
rules: [{
test: /.css$/,
use: [
'vue-style-loader',
'css-loader'
]
},{
test: /.scss$/,
use: [
'vue-style-loader',
'css-loader',
'sass-loader'
]
},
{
test: /.sass$/,
use: [
'vue-style-loader',
'css-loader',
'sass-loader?indentedSyntax'
]
}]
},<p>以上配置意爲:<br><code>.css</code>爲後綴的文件使用<code>css-loader</code>, <code>vue-style-loader</code>解析<br><code>.scss</code>和<code>.sass</code>爲後綴的文件使用<code>sass-loader</code>,<code>css-loader</code>, <code>vue-style-loader</code>解析<br>解析順序是由下到上的</p> <blockquote>webpack - module:<a href="https://webpack.docschina.org/configuration/module/#module-rules" rel="nofollow noreferrer">https://webpack.docschina.org...</a><br>webpack - sass-loader:<a href="https://webpack.docschina.org/loaders/sass-loader/" rel="nofollow noreferrer">https://webpack.docschina.org...</a> </blockquote> <h3>在項目中使用、引入樣式(測試)</h3> <p>在src目錄下新建目錄assets/styles存放統同樣式,新建index.scss,寫一段scss代碼:</p> <pre><code class="scss">$appColor:red; #app{ color:$appColor; }
在main.js中引入樣式:
import ‘./assets/styles/index.scss’
再次重啓服務能夠看到樣式已經加載成功了
5. 配置loader——使用圖片
一樣webpack人沒法解析圖片格式的文件,須要把圖片當作模塊使用file-loader解析。
file-loader: https://webpack.docschina.org...安裝file-loader
<p>關於webpack解析樣式的文檔比較散亂,經過粗略查閱,<br><code>css-loader</code>用來解析css文件,<br><code>style-loader</code>用來解析dom中經過<code><style></style></code>注入的樣式,<br>而<code>vue-style-loader</code>是vue官方基於style-loader開發的適用於vue的樣式解析,<br><code>sass-loader</code>用來解析sass/scss文件</p> <blockquote>webpack - loader:<a href="https://webpack.docschina.org/loaders/" rel="nofollow noreferrer">https://webpack.docschina.org...</a><br>vue-style-loader:<a href="https://www.npmjs.com/package/vue-style-loader" rel="nofollow noreferrer">https://www.npmjs.com/package...</a> </blockquote> <h3>在webpack.config.js中配置解析器</h3><p>以上配置意爲:<br><code>.css</code>爲後綴的文件使用<code>css-loader</code>, <code>vue-style-loader</code>解析<br><code>.scss</code>和<code>.sass</code>爲後綴的文件使用<code>sass-loader</code>,<code>css-loader</code>, <code>vue-style-loader</code>解析<br>解析順序是由下到上的</p> <blockquote>webpack - module:<a href="https://webpack.docschina.org/configuration/module/#module-rules" rel="nofollow noreferrer">https://webpack.docschina.org...</a><br>webpack - sass-loader:<a href="https://webpack.docschina.org/loaders/sass-loader/" rel="nofollow noreferrer">https://webpack.docschina.org...</a> </blockquote> <h3>在項目中使用、引入樣式(測試)</h3> <p>在src目錄下新建目錄assets/styles存放統同樣式,新建index.scss,寫一段scss代碼:</p> <pre><code class="scss">$appColor:red; #app{ color:$appColor; }import ‘./assets/styles/index.scss’npm i file-loader --save-dev
npm i file-loader --save-dev
<h3>在webpack.config.js中配置解析器</h3>
{
test: /.(png|jpg|gif|svg)$/,
loader: 'file-loader',
options: {
name: '[name].[ext]?[hash]'
}
}<h3>在項目中引入圖片(測試)</h3> <p>在src目錄下按照代碼中路徑準備一張圖片</p>
Vue.component('myComponent', {
template: '<img :src="url" />',
data() {
return {
url: require('./assets/images/logo.png')
}
}
})```
在index.html中使用該組件
```<div id="app">
{{message}}
<my-component></my-component>
</div><p>重啓服務,圖片應該被成功加載了。</p> <h2>6. 配置loader——使用babel</h2> <p>babel可讓咱們在項目中自由的使用es6語法,他會爲咱們將es6語法編譯成瀏覽器廣泛通用的es5語法。<br>在此以前咱們必需要對babel有必定的瞭解:</p> <blockquote>babel官方文檔:<a href="https://babel.docschina.org/docs/en/usage" rel="nofollow noreferrer">https://babel.docschina.org/d...</a> </blockquote> <p>在babel的使用指南中咱們看到安裝babel須要安裝的依賴和配置babel的方法。<br>而且咱們得知一個噩耗,babel從7.0開始與以前版本有寫不兼容了。若是你的package.json中babel的版本混亂,很容易形成配置失敗。</p> <h3>安裝babel</h3> <pre><code class="coffeescript">npm install --save-dev @babel/core @babel/cli @babel/preset-env npm install --save @babel/polyfill
注意:
- 其中preset是babel的配置,babel-loader在webpack中解析babel中會用到,polyfill也是babel的一個依賴
- babel的6.0 和7.0不兼容,若是package.json中版本混亂建議降級活升級以統一版本
在webpack.config.js中配置解析器
babel的webpack配置: https://babel.docschina.org/s... 選擇webpackmodule增長一條rules:
{ test: /\.js$/, exclude: /node_modules/, loader: "babel-loader" }
入口文件更改成:
entry: ["@babel/polyfill", './src/main.js'],
新建配置文件.babelrc
注意查看關於env的配置文檔,新版本寫法有變化。
@babel/preset-env: https://babel.docschina.org/d...{ "presets": [ [ "@babel/preset-env", { "useBuiltIns": "entry" } ] ] }
檢測es6語法(正常運行說明babel配置成功)
在src下新建util.js
export default function getData() { return new Promise((resolve, reject) => { resolve('ok'); }) }
main.js
//引入組件 import getData from './util'; var app = new Vue({ el: "#app", data: { message: 'hello webpack!!' }, methods: { async fetchData() { const data = await getData(); this.message = data; } }, created() { this.fetchData(); } })
import getData from './util';
常見報錯
Can't resolve 'babel-polyfill' in 'E:\vue\webpack-vue'
webpack的入口文件polyfill版本與配置寫法不匹配
錯誤:entry: ["babel-polyfill", './src/main.js'],
正確:entry: ["@babel/polyfill", './src/main.js'],regeneratorRuntime is not defined
未安裝@babel/polyfill
npm i babel-polyfill –savePlugin/Preset files are not allowed to export objects
webpack的報錯,版本混亂,不兼容
清理package.json中的babel依賴,刪除node_module,從新執行npm install,再次安裝babel依賴時注意版本統一7. 使用Vue單文件組件
vue-loader中介紹瞭如何使用Vue單文件組件:
vue-loader: https://vue-loader.vuejs.org/zh/安裝vue-loader及依賴
npm i vue-loader vue-template-compiler –save-dev
<h3>配置webpack.config.js</h3> <blockquote>Vue單文件組件:<a href="https://vue-loader.vuejs.org/zh/guide/" rel="nofollow noreferrer">https://vue-loader.vuejs.org/...</a> </blockquote>
// webpack.config.js
const VueLoaderPlugin = require('vue-loader/lib/plugin')module.exports = {
module: {
rules: [
// ... 其它規則
{
test: /.vue$/,
loader: 'vue-loader'
}
]
},
plugins: [
// 請確保引入這個插件!
new VueLoaderPlugin()
]
}
```準備單文件組件
在src目錄下建立文件App.vue
在src目錄下新建目錄components用來存放單文件組件,新建文件header.vueApp.vue
<div> <home-header user="vict"></home-header> </div> </template> <script> import homeHeader from '@/components/header.vue' export default { name:'app', components:{ homeHeader } } </script> <style lang="scss" scoped> $txtColor:red; .sg{ color:$txtColor } </style>
header.vue(子組件)
<template> <div> header <span>color</span> <img src="@/assets/images/logo.png"> {{this.message}} - {{this.user}} </div> </template> <script> export default { name:'homeHeader', data () { return { message:'hello world' } }, props: { user:String } } </script> <style lang="scss" scoped> span{ color:green } </style>
main.js
import Vue from 'vue' import App from './App.vue' import './assets/styles/index.scss' new Vue({ render:h => h(App) }).$mount('#app')
8. 解決靜態文件
在.vue中url路徑將被解析成webpack模塊請求,
這裏建議在webpack.config.js中配置路徑別名以方便在單文件組件中引用圖片等靜態資源
在單文件組件中能夠這樣使用:
<img src="@/assets/images/logo.png">
9. 注入Vue Router
vue-router: https://router.vuejs.org/zh/安裝VueRouter
npm i vue-router –save
<h3>在main.js的Vue實例中注入Router</h3>
import Vue from 'vue'
import App from './App'
//引入router組件
import router from './router/router'
import './assets/styles/reset.css'new Vue({
//注入router
router,
render:h => h(App)
}).$mount('#app')<h3>構建router組件</h3> <p>按照路徑建立router文件:src/router/router.js</p> <p>router.js</p>
import Vue from 'vue'
import VueRouter from 'vue-router'import Page1 from '@/components/page1'
import Page2 from '@/components/page2'Vue.use(VueRouter)
export default new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes: [{
path: '/',
name:'home',
component: Page1
},{
path: '/page2',
name:'page2',
component: Page2
}]
})<p><em>常見的渲染失敗的緣由:</em></p> <ul> <li><em>router實例的路由配置項 routes,不要誤寫成 routers</em></li> <li><em>routes配置項中必需要有路徑爲’/’,不然渲染失敗</em></li> </ul> <h3>使用router</h3> <p>在App.vue中能夠直接使用<code><router-view></code>和<code><router-link></code>標籤</p> <h2>10. 注入Vuex</h2> <blockquote>vuex: <a href="https://vuex.vuejs.org/zh/guide/" rel="nofollow noreferrer">https://vuex.vuejs.org/zh/guide/</a> </blockquote> <h3>安裝vuex</h3> <pre><code class="coffeescript">npm i vuex –save
在main.js的Vue實例中注入store
import Vue from 'vue' import App from './App' import router from './router/router' import store from './store/store' import './assets/styles/reset.css' new Vue({ router, store, render:h => h(App) }).$mount('#app')
構建store目錄
src/store/store.js
可按須要將state、actions、mutations拆分出來store.js
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ state: { cur:'OFF', }, actions: { changeCur (ctx,cur) { ctx.commit('changeCueMutations',cur) } }, mutations: { changeCueMutations (state,cur) { cur == 'OFF' ? state.cur = 'ON' :state.cur = 'OFF' } } })
11. 打包發佈
webpack.config.js中若是配置項:mode:'development', build的結果是未通過壓縮的很是的大
修改 package.json 中的scripts,將打包時的mode切換成production"scripts": { "test": "echo \"Error: no test specified\" && exit 1", "dev": "webpack-dev-server --hot --open", "build": "webpack --mode production --progress --hide-modules" },
文檔彙總
webpack相關
webpack官方文檔: https://webpack.docschina.org/
webpack安裝: https://webpack.docschina.org...
webpack-dev-server: https://webpack.docschina.org...
webpack配置: https://webpack.docschina.org...
webpack命令行接口: https://webpack.docschina.org...
webpack解析(resolve): https://webpack.docschina.org...
webpack - loader: https://webpack.docschina.org...
webpack - module: https://webpack.docschina.org...Vue相關
Vue官方文檔(中文): https://cn.vuejs.org/
Vue-cli: https://cli.vuejs.org/zh/guide/
Vue-router: https://router.vuejs.org/
Vuex: https://vuex.vuejs.org/
Vue-loader(單文件組件): https://vue-loader.vuejs.org/babel相關
babel官方文檔: https://babel.docschina.org/
babel使用指南: https://babel.docschina.org/d...
babel的配置: https://babel.docschina.org/s...
babel-env: https://babel.docschina.org/d...其餘
npm官方: https://www.npmjs.com/
npm CLI(命令行指令): https://docs.npmjs.com/
vue-style-loader: https://www.npmjs.com/package...
node-sass: https://www.npmjs.com/search?...<h3>在webpack.config.js中配置解析器</h3>
{
test: /.(png|jpg|gif|svg)$/,
loader: 'file-loader',
options: {
name: '[name].[ext]?[hash]'
}
}<h3>在項目中引入圖片(測試)</h3> <p>在src目錄下按照代碼中路徑準備一張圖片</p>
Vue.component('myComponent', {
template: '<img :src="url" />',
data() {
return {
url: require('./assets/images/logo.png')
}
}
})```
在index.html中使用該組件
```<div id="app">
{{message}}
<my-component></my-component>
</div><p>重啓服務,圖片應該被成功加載了。</p> <h2>6. 配置loader——使用babel</h2> <p>babel可讓咱們在項目中自由的使用es6語法,他會爲咱們將es6語法編譯成瀏覽器廣泛通用的es5語法。<br>在此以前咱們必需要對babel有必定的瞭解:</p> <blockquote>babel官方文檔:<a href="https://babel.docschina.org/docs/en/usage" rel="nofollow noreferrer">https://babel.docschina.org/d...</a> </blockquote> <p>在babel的使用指南中咱們看到安裝babel須要安裝的依賴和配置babel的方法。<br>而且咱們得知一個噩耗,babel從7.0開始與以前版本有寫不兼容了。若是你的package.json中babel的版本混亂,很容易形成配置失敗。</p> <h3>安裝babel</h3> <pre><code class="coffeescript">npm install --save-dev @babel/core @babel/cli @babel/preset-env npm install --save @babel/polyfill
注意:
babel的webpack配置: https://babel.docschina.org/s... 選擇webpack
module增長一條rules:
{
test: /\.js$/, exclude: /node_modules/,
loader: "babel-loader"
}
入口文件更改成:
entry: ["@babel/polyfill", './src/main.js'],
注意查看關於env的配置文檔,新版本寫法有變化。
@babel/preset-env: https://babel.docschina.org/d...
{
"presets": [
[
"@babel/preset-env",
{
"useBuiltIns": "entry"
}
]
]
}
在src下新建util.js
export default function getData() {
return new Promise((resolve, reject) => {
resolve('ok');
})
}
main.js
//引入組件
import getData from './util';
var app = new Vue({
el: "#app",
data: {
message: 'hello webpack!!'
},
methods: {
async fetchData() {
const data = await getData();
this.message = data;
}
},
created() {
this.fetchData();
}
})
import getData from './util';
Can't resolve 'babel-polyfill' in 'E:\vue\webpack-vue'
regeneratorRuntime is not defined
Plugin/Preset files are not allowed to export objects
vue-loader中介紹瞭如何使用Vue單文件組件:
vue-loader: https://vue-loader.vuejs.org/zh/
<h3>在webpack.config.js中配置解析器</h3><h3>在項目中引入圖片(測試)</h3> <p>在src目錄下按照代碼中路徑準備一張圖片</p><p>重啓服務,圖片應該被成功加載了。</p> <h2>6. 配置loader——使用babel</h2> <p>babel可讓咱們在項目中自由的使用es6語法,他會爲咱們將es6語法編譯成瀏覽器廣泛通用的es5語法。<br>在此以前咱們必需要對babel有必定的瞭解:</p> <blockquote>babel官方文檔:<a href="https://babel.docschina.org/docs/en/usage" rel="nofollow noreferrer">https://babel.docschina.org/d...</a> </blockquote> <p>在babel的使用指南中咱們看到安裝babel須要安裝的依賴和配置babel的方法。<br>而且咱們得知一個噩耗,babel從7.0開始與以前版本有寫不兼容了。若是你的package.json中babel的版本混亂,很容易形成配置失敗。</p> <h3>安裝babel</h3> <pre><code class="coffeescript">npm install --save-dev @babel/core @babel/cli @babel/preset-env npm install --save @babel/polyfill{ test: /\.js$/, exclude: /node_modules/, loader: "babel-loader" }entry: ["@babel/polyfill", './src/main.js'],{ "presets": [ [ "@babel/preset-env", { "useBuiltIns": "entry" } ] ] }export default function getData() { return new Promise((resolve, reject) => { resolve('ok'); }) }//引入組件 import getData from './util'; var app = new Vue({ el: "#app", data: { message: 'hello webpack!!' }, methods: { async fetchData() { const data = await getData(); this.message = data; } }, created() { this.fetchData(); } })Can't resolve 'babel-polyfill' in 'E:\vue\webpack-vue'regeneratorRuntime is not definedPlugin/Preset files are not allowed to export objectsnpm i vue-loader vue-template-compiler –save-dev
npm i vue-loader vue-template-compiler –save-dev
<h3>配置webpack.config.js</h3> <blockquote>Vue單文件組件:<a href="https://vue-loader.vuejs.org/zh/guide/" rel="nofollow noreferrer">https://vue-loader.vuejs.org/...</a> </blockquote>
// webpack.config.js
const VueLoaderPlugin = require('vue-loader/lib/plugin')module.exports = {
module: {
rules: [
// ... 其它規則
{
test: /.vue$/,
loader: 'vue-loader'
}
]
},
plugins: [
// 請確保引入這個插件!
new VueLoaderPlugin()
]
}
```準備單文件組件
在src目錄下建立文件App.vue
在src目錄下新建目錄components用來存放單文件組件,新建文件header.vueApp.vue
<div> <home-header user="vict"></home-header> </div> </template> <script> import homeHeader from '@/components/header.vue' export default { name:'app', components:{ homeHeader } } </script> <style lang="scss" scoped> $txtColor:red; .sg{ color:$txtColor } </style>
header.vue(子組件)
<template> <div> header <span>color</span> <img src="@/assets/images/logo.png"> {{this.message}} - {{this.user}} </div> </template> <script> export default { name:'homeHeader', data () { return { message:'hello world' } }, props: { user:String } } </script> <style lang="scss" scoped> span{ color:green } </style>
main.js
import Vue from 'vue' import App from './App.vue' import './assets/styles/index.scss' new Vue({ render:h => h(App) }).$mount('#app')
8. 解決靜態文件
在.vue中url路徑將被解析成webpack模塊請求,
這裏建議在webpack.config.js中配置路徑別名以方便在單文件組件中引用圖片等靜態資源
在單文件組件中能夠這樣使用:
<img src="@/assets/images/logo.png">
9. 注入Vue Router
vue-router: https://router.vuejs.org/zh/安裝VueRouter
npm i vue-router –save
<h3>在main.js的Vue實例中注入Router</h3>
import Vue from 'vue'
import App from './App'
//引入router組件
import router from './router/router'
import './assets/styles/reset.css'new Vue({
//注入router
router,
render:h => h(App)
}).$mount('#app')<h3>構建router組件</h3> <p>按照路徑建立router文件:src/router/router.js</p> <p>router.js</p>
import Vue from 'vue'
import VueRouter from 'vue-router'import Page1 from '@/components/page1'
import Page2 from '@/components/page2'Vue.use(VueRouter)
export default new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes: [{
path: '/',
name:'home',
component: Page1
},{
path: '/page2',
name:'page2',
component: Page2
}]
})<p><em>常見的渲染失敗的緣由:</em></p> <ul> <li><em>router實例的路由配置項 routes,不要誤寫成 routers</em></li> <li><em>routes配置項中必需要有路徑爲’/’,不然渲染失敗</em></li> </ul> <h3>使用router</h3> <p>在App.vue中能夠直接使用<code><router-view></code>和<code><router-link></code>標籤</p> <h2>10. 注入Vuex</h2> <blockquote>vuex: <a href="https://vuex.vuejs.org/zh/guide/" rel="nofollow noreferrer">https://vuex.vuejs.org/zh/guide/</a> </blockquote> <h3>安裝vuex</h3> <pre><code class="coffeescript">npm i vuex –save
在main.js的Vue實例中注入store
import Vue from 'vue' import App from './App' import router from './router/router' import store from './store/store' import './assets/styles/reset.css' new Vue({ router, store, render:h => h(App) }).$mount('#app')
構建store目錄
src/store/store.js
可按須要將state、actions、mutations拆分出來store.js
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ state: { cur:'OFF', }, actions: { changeCur (ctx,cur) { ctx.commit('changeCueMutations',cur) } }, mutations: { changeCueMutations (state,cur) { cur == 'OFF' ? state.cur = 'ON' :state.cur = 'OFF' } } })
11. 打包發佈
webpack.config.js中若是配置項:mode:'development', build的結果是未通過壓縮的很是的大
修改 package.json 中的scripts,將打包時的mode切換成production"scripts": { "test": "echo \"Error: no test specified\" && exit 1", "dev": "webpack-dev-server --hot --open", "build": "webpack --mode production --progress --hide-modules" },
文檔彙總
webpack相關
webpack官方文檔: https://webpack.docschina.org/
webpack安裝: https://webpack.docschina.org...
webpack-dev-server: https://webpack.docschina.org...
webpack配置: https://webpack.docschina.org...
webpack命令行接口: https://webpack.docschina.org...
webpack解析(resolve): https://webpack.docschina.org...
webpack - loader: https://webpack.docschina.org...
webpack - module: https://webpack.docschina.org...Vue相關
Vue官方文檔(中文): https://cn.vuejs.org/
Vue-cli: https://cli.vuejs.org/zh/guide/
Vue-router: https://router.vuejs.org/
Vuex: https://vuex.vuejs.org/
Vue-loader(單文件組件): https://vue-loader.vuejs.org/babel相關
babel官方文檔: https://babel.docschina.org/
babel使用指南: https://babel.docschina.org/d...
babel的配置: https://babel.docschina.org/s...
babel-env: https://babel.docschina.org/d...其餘
npm官方: https://www.npmjs.com/
npm CLI(命令行指令): https://docs.npmjs.com/
vue-style-loader: https://www.npmjs.com/package...
node-sass: https://www.npmjs.com/search?...
<h3>配置webpack.config.js</h3>
<blockquote>Vue單文件組件:<a href="https://vue-loader.vuejs.org/zh/guide/" rel="nofollow noreferrer">https://vue-loader.vuejs.org/...</a>
</blockquote>
// webpack.config.js
const VueLoaderPlugin = require('vue-loader/lib/plugin')
module.exports = {
module: {
rules: [
// ... 其它規則
{
test: /.vue$/,
loader: 'vue-loader'
}
]
},
plugins: [
// 請確保引入這個插件!
new VueLoaderPlugin()
]
}
```
在src目錄下建立文件App.vue
在src目錄下新建目錄components用來存放單文件組件,新建文件header.vue
App.vue
<div>
<home-header user="vict"></home-header>
</div>
</template>
<script>
import homeHeader from '@/components/header.vue'
export default {
name:'app',
components:{
homeHeader
}
}
</script>
<style lang="scss" scoped>
$txtColor:red;
.sg{
color:$txtColor
}
</style>
header.vue(子組件)
<template>
<div>
header
<span>color</span>
<img src="@/assets/images/logo.png">
{{this.message}} - {{this.user}}
</div>
</template>
<script>
export default {
name:'homeHeader',
data () {
return {
message:'hello world'
}
},
props: {
user:String
}
}
</script>
<style lang="scss" scoped>
span{
color:green
}
</style>
main.js
import Vue from 'vue'
import App from './App.vue'
import './assets/styles/index.scss'
new Vue({
render:h => h(App)
}).$mount('#app')
在.vue中url路徑將被解析成webpack模塊請求,
這裏建議在webpack.config.js中配置路徑別名以方便在單文件組件中引用圖片等靜態資源
在單文件組件中能夠這樣使用:
<img src="@/assets/images/logo.png">
vue-router: https://router.vuejs.org/zh/
<h3>配置webpack.config.js</h3> <blockquote>Vue單文件組件:<a href="https://vue-loader.vuejs.org/zh/guide/" rel="nofollow noreferrer">https://vue-loader.vuejs.org/...</a> </blockquote><div> <home-header user="vict"></home-header> </div> </template> <script> import homeHeader from '@/components/header.vue' export default { name:'app', components:{ homeHeader } } </script> <style lang="scss" scoped> $txtColor:red; .sg{ color:$txtColor } </style><template> <div> header <span>color</span> <img src="@/assets/images/logo.png"> {{this.message}} - {{this.user}} </div> </template> <script> export default { name:'homeHeader', data () { return { message:'hello world' } }, props: { user:String } } </script> <style lang="scss" scoped> span{ color:green } </style>import Vue from 'vue' import App from './App.vue' import './assets/styles/index.scss' new Vue({ render:h => h(App) }).$mount('#app')<img src="@/assets/images/logo.png">npm i vue-router –save
npm i vue-router –save
<h3>在main.js的Vue實例中注入Router</h3>
import Vue from 'vue'
import App from './App'
//引入router組件
import router from './router/router'
import './assets/styles/reset.css'new Vue({
//注入router
router,
render:h => h(App)
}).$mount('#app')<h3>構建router組件</h3> <p>按照路徑建立router文件:src/router/router.js</p> <p>router.js</p>
import Vue from 'vue'
import VueRouter from 'vue-router'import Page1 from '@/components/page1'
import Page2 from '@/components/page2'Vue.use(VueRouter)
export default new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes: [{
path: '/',
name:'home',
component: Page1
},{
path: '/page2',
name:'page2',
component: Page2
}]
})<p><em>常見的渲染失敗的緣由:</em></p> <ul> <li><em>router實例的路由配置項 routes,不要誤寫成 routers</em></li> <li><em>routes配置項中必需要有路徑爲’/’,不然渲染失敗</em></li> </ul> <h3>使用router</h3> <p>在App.vue中能夠直接使用<code><router-view></code>和<code><router-link></code>標籤</p> <h2>10. 注入Vuex</h2> <blockquote>vuex: <a href="https://vuex.vuejs.org/zh/guide/" rel="nofollow noreferrer">https://vuex.vuejs.org/zh/guide/</a> </blockquote> <h3>安裝vuex</h3> <pre><code class="coffeescript">npm i vuex –save
在main.js的Vue實例中注入store
import Vue from 'vue' import App from './App' import router from './router/router' import store from './store/store' import './assets/styles/reset.css' new Vue({ router, store, render:h => h(App) }).$mount('#app')
構建store目錄
src/store/store.js
可按須要將state、actions、mutations拆分出來store.js
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ state: { cur:'OFF', }, actions: { changeCur (ctx,cur) { ctx.commit('changeCueMutations',cur) } }, mutations: { changeCueMutations (state,cur) { cur == 'OFF' ? state.cur = 'ON' :state.cur = 'OFF' } } })
11. 打包發佈
webpack.config.js中若是配置項:mode:'development', build的結果是未通過壓縮的很是的大
修改 package.json 中的scripts,將打包時的mode切換成production"scripts": { "test": "echo \"Error: no test specified\" && exit 1", "dev": "webpack-dev-server --hot --open", "build": "webpack --mode production --progress --hide-modules" },
文檔彙總
webpack相關
webpack官方文檔: https://webpack.docschina.org/
webpack安裝: https://webpack.docschina.org...
webpack-dev-server: https://webpack.docschina.org...
webpack配置: https://webpack.docschina.org...
webpack命令行接口: https://webpack.docschina.org...
webpack解析(resolve): https://webpack.docschina.org...
webpack - loader: https://webpack.docschina.org...
webpack - module: https://webpack.docschina.org...Vue相關
Vue官方文檔(中文): https://cn.vuejs.org/
Vue-cli: https://cli.vuejs.org/zh/guide/
Vue-router: https://router.vuejs.org/
Vuex: https://vuex.vuejs.org/
Vue-loader(單文件組件): https://vue-loader.vuejs.org/babel相關
babel官方文檔: https://babel.docschina.org/
babel使用指南: https://babel.docschina.org/d...
babel的配置: https://babel.docschina.org/s...
babel-env: https://babel.docschina.org/d...其餘
npm官方: https://www.npmjs.com/
npm CLI(命令行指令): https://docs.npmjs.com/
vue-style-loader: https://www.npmjs.com/package...
node-sass: https://www.npmjs.com/search?...
<h3>在main.js的Vue實例中注入Router</h3>
import Vue from 'vue'
import App from './App'
//引入router組件
import router from './router/router'
import './assets/styles/reset.css'
new Vue({
//注入router
router,
render:h => h(App)
}).$mount('#app')
<h3>構建router組件</h3>
<p>按照路徑建立router文件:src/router/router.js</p>
<p>router.js</p>
import Vue from 'vue'
import VueRouter from 'vue-router'
import Page1 from '@/components/page1'
import Page2 from '@/components/page2'
Vue.use(VueRouter)
export default new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes: [{
path: '/',
name:'home',
component: Page1
},{
path: '/page2',
name:'page2',
component: Page2
}]
})
<p><em>常見的渲染失敗的緣由:</em></p>
<ul>
<li><em>router實例的路由配置項 routes,不要誤寫成 routers</em></li>
<li><em>routes配置項中必需要有路徑爲’/’,不然渲染失敗</em></li>
</ul>
<h3>使用router</h3>
<p>在App.vue中能夠直接使用<code><router-view></code>和<code><router-link></code>標籤</p>
<h2>10. 注入Vuex</h2>
<blockquote>vuex: <a href="https://vuex.vuejs.org/zh/guide/" rel="nofollow noreferrer">https://vuex.vuejs.org/zh/guide/</a>
</blockquote>
<h3>安裝vuex</h3>
<pre><code class="coffeescript">npm i vuex –save
import Vue from 'vue'
import App from './App'
import router from './router/router'
import store from './store/store'
import './assets/styles/reset.css'
new Vue({
router,
store,
render:h => h(App)
}).$mount('#app')
src/store/store.js
可按須要將state、actions、mutations拆分出來
store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
cur:'OFF',
},
actions: {
changeCur (ctx,cur) {
ctx.commit('changeCueMutations',cur)
}
},
mutations: {
changeCueMutations (state,cur) {
cur == 'OFF' ? state.cur = 'ON' :state.cur = 'OFF'
}
}
})
webpack.config.js中若是配置項:mode:'development', build的結果是未通過壓縮的很是的大
修改 package.json 中的scripts,將打包時的mode切換成production
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "webpack-dev-server --hot --open",
"build": "webpack --mode production --progress --hide-modules"
},
webpack官方文檔: https://webpack.docschina.org/
webpack安裝: https://webpack.docschina.org...
webpack-dev-server: https://webpack.docschina.org...
webpack配置: https://webpack.docschina.org...
webpack命令行接口: https://webpack.docschina.org...
webpack解析(resolve): https://webpack.docschina.org...
webpack - loader: https://webpack.docschina.org...
webpack - module: https://webpack.docschina.org...
Vue官方文檔(中文): https://cn.vuejs.org/
Vue-cli: https://cli.vuejs.org/zh/guide/
Vue-router: https://router.vuejs.org/
Vuex: https://vuex.vuejs.org/
Vue-loader(單文件組件): https://vue-loader.vuejs.org/
babel官方文檔: https://babel.docschina.org/
babel使用指南: https://babel.docschina.org/d...
babel的配置: https://babel.docschina.org/s...
babel-env: https://babel.docschina.org/d...
npm官方: https://www.npmjs.com/<h3>在main.js的Vue實例中注入Router</h3><h3>構建router組件</h3> <p>按照路徑建立router文件:src/router/router.js</p> <p>router.js</p><p><em>常見的渲染失敗的緣由:</em></p> <ul> <li><em>router實例的路由配置項 routes,不要誤寫成 routers</em></li> <li><em>routes配置項中必需要有路徑爲’/’,不然渲染失敗</em></li> </ul> <h3>使用router</h3> <p>在App.vue中能夠直接使用<code><router-view></code>和<code><router-link></code>標籤</p> <h2>10. 注入Vuex</h2> <blockquote>vuex: <a href="https://vuex.vuejs.org/zh/guide/" rel="nofollow noreferrer">https://vuex.vuejs.org/zh/guide/</a> </blockquote> <h3>安裝vuex</h3> <pre><code class="coffeescript">npm i vuex –saveimport Vue from 'vue' import App from './App' import router from './router/router' import store from './store/store' import './assets/styles/reset.css' new Vue({ router, store, render:h => h(App) }).$mount('#app')import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ state: { cur:'OFF', }, actions: { changeCur (ctx,cur) { ctx.commit('changeCueMutations',cur) } }, mutations: { changeCueMutations (state,cur) { cur == 'OFF' ? state.cur = 'ON' :state.cur = 'OFF' } } })"scripts": { "test": "echo \"Error: no test specified\" && exit 1", "dev": "webpack-dev-server --hot --open", "build": "webpack --mode production --progress --hide-modules" },
npm CLI(命令行指令): https://docs.npmjs.com/
vue-style-loader: https://www.npmjs.com/package...
node-sass: https://www.npmjs.com/search?...