webpack4+加vue2+從零開始搭設vue項目

@TOCjavascript

本地環境css

node -v    // v9.1.0
npm -v  // 6.5.0

webpack -v   // 4.32.2
webpack-cli -v // 3.3.2
複製代碼

這裏須要注意的是webpack4+之後須要單獨安裝webpack-clihtml

起步

1.初始化項目

npm init 
複製代碼

一直enter生成package.json文件(小技巧:npm init -y 能夠免去繁瑣的enter)vue

2.安裝依賴

npm i webpack webpack-cli webpack-dev-server --save-dev
複製代碼

想要深刻上述依賴請轉webpack文檔java

依賴安裝成功接下來就開始動手吧node

3.目錄文件配置

根目錄鼠標右鍵新建index.html webpack.config.js src文件夾或:webpack

// window
type >webpcak.config.js 
type >index.html 
md src

//mac 土豪玩家
touch webpcak.config.js 
touch index.html
mkdir src
複製代碼

src目錄下面新建 main.jsnginx

此時目錄以下git

project/
        src/
            main.js
        webpack.config.js
        index.html
        package.json

複製代碼

內容以下:es6

//index.html
<!DOCTYPE html>
<html lang="en"> <head> <meta charset="UTF-8"> <title>webpack從零搭設</title> </head> <body> <div id="app"></div> </body> </html> 複製代碼
// webpack.config.js
const path = require('path');
const webpack = require('webpack');
modul.exports = {}
複製代碼

4.配置index.html及webpack.config.js

首先 main.js修改以下:

// src/main.js
console.log('hello world');
複製代碼

webpack.config.js修改以下:

// webpack.config.js
const path = require('path');
const webpack = require('webpack');

module.exports = {  // module.exports commonjs規範
  entry: './src/main.js', // 項目入口文件,webpack將從main.js開始,把全部依賴的js都打包
  output: {
    path: path.resolve(__dirname, './dist'), // 項目的打包後的輸出路徑 可修改
    publicPath: '/dist/', // 經過devServer訪問路徑 可修改
    filename: 'build.js' // 打包後的文件名 可修改
  },
  devServer: {
    historyApiFallback: true, // When using the HTML5 History API, the `index.html` page will likely have to be served in place of any `404` responses
    overlay: true //Shows a full-screen overlay in the browser when there are compiler errors or warnings. Disabled by default. If you want to show only compiler errors
  },
};

複製代碼

index.html 修改以下 增長引入打包後的js

// index.html
<!DOCTYPE html>
<html lang="en"> <head> <meta charset="UTF-8"> <title>webpack從零搭設</title> </head> <body> <div id="app"></div> </body> <script src="/dist/build.js"></script> </html> 複製代碼

package.json修改以下:

"scripts": {
    "dev": "webpack-dev-server --open --hot",
    "build": "webpack --progress --hide-modules"
  },
複製代碼

webpack-dev-server會啓動一個靜態資源web服務器 --hot參數表示啓動熱更新

從新啓動服務

npm run dev
複製代碼

打開控制檯能夠看到 有輸出hello world

控制檯輸出hello world

5.vue的起步

安裝vue

npm install vue --save
複製代碼

修改main.js以下

// src/main.js
import Vue from 'vue';
// import Vue from 'vue/dist/vue.esm.js'  // 解決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

// console.log('hello world');

var app = new Vue({
  el: '#app',
  data: {
    mess: 'Hello Vue@2.0!'
  }
})

複製代碼

此時 修改index.html以下:

// index.html
<!DOCTYPE html>
<html lang="en"> <head> <meta charset="UTF-8"> <title>webpack從零搭設</title> </head> <body> <div id="app"> {{ mess }} </div> </body> <script src="/dist/build.js"></script> </html> 複製代碼

從新啓動服務

npm run build
npm run dev
複製代碼

此時

控制檯報錯,頁面也未顯示hello Vue!

查閱資料發現: vue有兩種形式的代碼 compiler(模板)模式和runtime模式(運行) vue模塊的package.json的main字段默認爲runtime模式, 指向"dist/vue.runtime.common.js"位置。這是vue升級到2.0以後就有的特色。

但此時咱們main.js的寫法是

// src/main.js
import Vue from 'vue';
// import Vue from 'vue/dist/vue.esm.js'  // 解決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

// console.log('hello world');

var app = new Vue({
  el: '#app',
  data: {
    mess: 'Hello Vue@2.0!'
  }
})

複製代碼
解決方案 一
// src/main.js
//import Vue from 'vue';
 import Vue from 'vue/dist/vue.esm.js'  // 解決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

// console.log('hello world');

var app = new Vue({
  el: '#app',
  data: {
    mess: 'Hello Vue@2.0!'
  }
})

複製代碼

由於vue2.0默認的是runtime模式,須要藉助如 webpack 的 vue-loader 工具把 .vue 文件編譯成 JavaScript代碼;

解決方案 二(常規操做)
// webpack.config.js
const path = require('path');
const webpack = require('webpack');

module.exports = {  //module.exports commonjs規範
  entry: './src/main.js', // 項目的入口文件,webpack會從main.js開始,把全部依賴的js都加載打包
  output: {
    path: path.resolve(__dirname, './dist'), // 項目的打包文件路徑
    publicPath: '/dist/', // 經過devServer訪問路徑
    filename: 'build.js' // 打包後的文件名
  },
  devServer: {
    historyApiFallback: true,
    overlay: true
  },
  resolve: { // 修改別名,import Vue from ‘vue’ 這行代碼被解析爲 import Vue from ‘vue/dist/vue.esm.js
    alias: {
      'vue$': 'vue/dist/vue.esm.js'
    }
  },
};

複製代碼

這個修改和上次是同樣的意思,不過相對雅觀不少...

解決方案 三

修改main.js的模式

  1. compiler 模式
// src/main.js
// compiler 模式
new Vue({
  el: '#app',
})
複製代碼

2.runtime 模式

//runtime模式
new Vue({
render: h => h(App)  // App.vue
}).$mount("#app")
複製代碼

將1換成2,但咱們推薦使用方案二;

最後 頁面展現以下:

hello Vue@2.0

引入css和scss

webpack默認支持的是js的模塊化,若是須要其餘類型文件也支持模塊化開發,則須要引入相應的loader用以解析!

安裝相關依賴

npm i node-sass css-loader vue-style-loader sass-loader --save-dev
複製代碼

webpack.config.js 修改以下

// webpack.config.js
const path = require('path');
const webpack = require('webpack');

module.exports = {  //module.exports commonjs規範
  entry: './src/main.js', // 項目的入口文件,webpack會從main.js開始,把全部依賴的js都加載打包
  output: {
    path: path.resolve(__dirname, './dist'), // 項目的打包文件路徑
    publicPath: '/dist/', // 經過devServer訪問路徑
    filename: 'build.js' // 打包後的文件名
  },
  devServer: {
    historyApiFallback: true,
    overlay: true
  },
  resolve: {
    alias: {
      'vue$': 'vue/dist/vue.esm.js'
    }
  },
   module: {
     rules: [
       {
         test: /\.css$/,
         use: [
           'vue-style-loader',
           'css-loader'
         ],
       },
       { // scss
         test: /\.scss$/,
         use: [
           'vue-style-loader',
           'css-loader',
           'sass-loader'
         ],
       }
     ]
   }
};

複製代碼

此時scss 及 css都能在開發中使用而且模塊化引入了

語法轉譯 ES6 => ES5

引入相關依賴 利用bable轉譯

npm i babel-core babel-loader babel-preset-env babel-preset-stage-3 --save-dev
複製代碼

其中 babel-preset-stage是不一樣階段語法提案的轉碼規則(共有4個階段),選裝一個,其中0最厲害

npm install --save-dev babel-preset-stage-0 npm install --save-dev babel-preset-stage-1 npm install --save-dev babel-preset-stage-2 npm install --save-dev babel-preset-stage-3

// .babelrc
{
  "presets": [
    ["env", { "modules": false }],
    "stage-3"
  ]
}

複製代碼

同時修改 webpack.config.js

// webpack.config.js
const path = require('path');
const webpack = require('webpack');

module.exports = {  //module.exports commonjs規範
  entry: './src/main.js', // 項目的入口文件,webpack會從main.js開始,把全部依賴的js都加載打包
  output: {
    path: path.resolve(__dirname, './dist'), // 項目的打包文件路徑
    publicPath: '/dist/', // 經過devServer訪問路徑
    filename: 'build.js' // 打包後的文件名
  },
  devServer: {
    historyApiFallback: true,
    overlay: true
  },
  resolve: {
    alias: {
      'vue$': 'vue/dist/vue.esm.js'
    }
  },
   module: {
     rules: [
       {
         test: /\.css$/,
         use: [
           'vue-style-loader',
           'css-loader'
         ],
       },
       { // scss
         test: /\.scss$/,
         use: [
           'vue-style-loader',
           'css-loader',
           'sass-loader'
         ],
       },
       { // 添加解析js的loader
         test: /\.js$/,
         loader: 'babel-loader',
         exclude: /node_modules/
       }
     ]
   }
};

複製代碼

此時咱們修改main.js嘗試使用es6語法

// src/main.js
import Vue from 'vue';
// import Vue from 'vue/dist/vue.esm.js' // 解決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


// console.log('hello world');

const say = function () {
  return new Promise((resolve, reject) => {
    resolve('I am es6');
  })
}


var app = new Vue({
  el: '#app',
  data: {
    mess: 'Hello Vue@2.0!'
  },
  methods: {
    updateData() {
      say().then((res)=>{
        this.mess = res;
      });
    },
    
  },
  created() {
    this.updateData();
  }
})

複製代碼

此時頁面輸出效果以下

I am es6
雖然知足咱們使用了,那麼接下來咱們嘗試一下ES7支持與否 main.js修改以下:

import Vue from 'vue';
// import Vue from 'vue/dist/vue.esm.js' // 解決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


// console.log('hello world');

const say = function () {
  return new Promise((resolve, reject) => {
    resolve('I am es7');
  })
}


var app = new Vue({
  el: '#app',
  data: {
    mess: 'Hello Vue@2.0!'
  },
  methods: {
    /*updateData() { say().then((res)=>{ this.mess = res; }); },*/
    async updateData() {
      const mess = await say();
      this.mess = mess;
    }
  },
  created() {
    this.updateData();
  }
})

複製代碼

頁面展現以下:

ES7測試
此時看到控制檯報錯

"ReferenceError: regeneratorRuntime is not defined"

查閱相關文章發現, 要想對es7語法進行支持,還須要安裝相關依賴進行轉譯;

這裏有兩種方案
方案一
npm i --save-dev babel-plugin-transform-runtime
複製代碼

修改.babelrc文件

// .babelrc
{
	"presets": [
		["env", { "modules": false }],
		"stage-3"
	],
	"plugins": [[  //  參考 https://www.jianshu.com/p/7a7f7abcddb5
		"transform-runtime",
		{
			"helpers": false,
			"polyfill": false,
			"regenerator": true,
			"moduleName": "babel-runtime"
		}
	]]
}
複製代碼

這裏順帶解釋一下preset與babel的關係:

  • preset中已經包含了一組用來轉換ES6+的語法的插件,若是隻使用少數新特性而非大多數新特性,能夠不使用preset而只使用對應的轉換插件
  • babel默認只轉換語法,而不轉換新的API,如需使用新的API,還須要使用對應的轉換插件或者polyfill

例如,默認狀況下babel能夠將箭頭函數,class等語法轉換爲ES5兼容的形式,可是卻不能轉換Map,Set,Promise等新的全局對象,這時候就須要使用polyfill去模擬這些新特性

此時看到頁面輸出正常:

ES7正常

方案二

全局babel-polyfill

npm i babel-polyfill --save-dev
複製代碼

webpack.config.js修改以下 注意看註釋

// webpack.config.js
  // entry: './src/main.js', // 項目的入口文件,webpack會從main.js開始,把全部依賴的js都加載打包
  entry: ['babel-polyfill', './src/main.js'], // 項目的入口文件,webpack會從main.js開始,把全部依賴的js都加載打包 參考 https://www.jianshu.com/p/3b27dfc6785c
複製代碼

此時從新跑項目npm run dev 結果方案一

es6與es7轉譯部分參考文章 babel-polyfill的幾種使用方式 babel的使用

文章最後

項目搭建,缺啥補啥!! 項目完整地址查看@王一諾wlove_c/webpack4.0+vue2.0

2019年6月16日文章更新webpack代理配置

這次更新的緣由是在一個技術分享羣有同窗問到\color{red}{webpack如何設置代理帶本地開發項目},當時有點懵,webpack都更新到4.34.0了還有同窗不會設置代理,因此藉助這邊文章更新一下代理配置;

安裝依賴 webpack-dev-server

npm install webpack-dev-server --save-dev
複製代碼

實際上webpack是經過http-proxy-middleware來做方向代理解決跨域的,詳情有興趣的同窗能夠本身瞭解一下

修改配置以下

// webpack.config.js
const path = require('path');
const webpack = require('webpack');

module.exports = {  //module.exports commonjs規範
   ...

  devServer: {
    historyApiFallback: true,
    overlay: true,
    proxy: {
      '/api': {
        target: 'http://localhost:3000', // 接口的域名和端口 若是端口爲80則能夠不寫
        pathRewrite: {'^/api' : ''}, // 若是不是以api開頭的能夠清空
        changeOrigin: true,     // target是域名的話,須要這個參數,
        secure: false,          // 默認狀況下,不接受運行在 HTTPS 上,且使用了無效證書的後端服務器。若是你想要接受,修改配置以下:
        },
    },
  },

   ...
};

複製代碼

此時你跑項目的時候 npm run dev 時 你會發現,請求到 /api/users 如今會被代理到請求 http://localhost:3000/api/users。 而且不會有跨域問題!不事後端同窗要容許跨域或者設置域名白名單喔

更多webpack-dev-server配置能夠轉@webpack/devserver-proxy

若是你想要nginx做代理的話也是能夠滴;詳情請轉個人另外一篇文章@王一諾Eno的文章nginx部署/代理/跨域

相關文章
相關標籤/搜索