1. 程式人生 > >Vue2、webpack、express4新建vue專案

Vue2、webpack、express4新建vue專案

1.環境:

Vue專案通常是由webpack工具來構建,而webpack命令的執行是依賴node.js的環境的,所以首先要安裝node.js。

2.新建專案:

(1)通過應用生成器工具 express-generator 快速建立一個應用的骨架。

安裝express-generator :Windows鍵+r輸入cmd執行npm install express-generator -g 

我用如下命令建立了一個名稱為William的 Express 應用。

如圖所示我在C:Users\thIinkpad目錄下就生成了專案的骨架。

(2)在根目錄下新建index.html。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div id="app"></div>
</body>
</html>

(3)在根目錄下新建src資料夾,然後建立app.vue和main.js。

app.vue程式碼:

<template>
    <div>山下蘭芽短浸溪,鬆間沙路淨無泥。</div>
</template>
<script>
    export default {
        name: "app"
    }
</script>
<style scoped>
    div{
        margin: auto;
        text-align: center;
    }
</style>

main.js程式碼:

import Vue from "vue";
import App from "./app";
new Vue({
    el:'#app', 
    render:h=> h(App)
});

提示:因為我用的是WebStorm,所以要將JavaScript language version設定成ECMAScript6,不然會報錯誤提示。

(4)將package.json檔案替換,程式碼如下:

{  "name": "myapp",
  "version": "0.0.0",
  "private": true,
  "scripts": {    "start": "node ./bin/www"  },
  "devDependencies": {
    "babel-core": "^6.20.0",
    "babel-loader": "^6.2.9",
    "babel-plugin-transform-runtime": "^6.15.0",
    "babel-preset-es2015": "^6.18.0",
    "babel-runtime": "^5.8.38",
    "babel-preset-stage-2": "^6.18.0",
    "html-webpack-plugin": "^2.24.1",
    "vue-html-loader": "^1.2.3",
    "css-loader": "^0.26.1",
    "vue-loader": "^10.0.2",
    "vue-template-compiler": "^2.1.6",
    "webpack": "^1.14.0",
    "webpack-dev-middleware": "^1.6.1"
  },
  "dependencies": {
    "express": "^4.14.0",
    "vue": "^2.1.6",
    "vue-router": "^2.1.1"
  }
}

(5)在根目錄下新建build資料夾,在資料夾內建立webpack.base.conf.js檔案,程式碼如下:

// nodejs 中的path模組
var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var  webpackConf = {
    // 入口檔案,path.resolve()方法,可以結合我們給定的兩個引數最後生成絕對路徑,最終指向的就是我們的index.js檔案
    entry: {  index: [   path.resolve(__dirname, '../src/main.js')  ] },
    // 輸出配置
    output: {  // 輸出路徑是 myProject/output/static
        path: path.resolve(__dirname, '../output'),//用來存放打包後文件的輸出目錄
        publicPath:'/',  filename: '[name].[hash].js'//指定資原始檔引用的目錄
    },
    resolve: {
        extensions: ['', '.js', '.vue'],
        alias: {   'vue': 'vue/dist/vue.js'  } // 設定別名vue1不需要設定,vue2必須設定 否則會報錯
    },
    module: {
        loaders: [
            // 使用vue-loader 載入 .vue 結尾的檔案
            {    test: /\.vue$/,    loader: 'vue'   },
            {    test: /\.js$/,    loader: 'babel',    exclude: /node_modules/   }  ]
    },
    vue: {  loaders: {   js: 'babel'  } },
    plugins:[
        new HtmlWebpackPlugin({
            filename: 'index.html',
            template: path.resolve(__dirname, '../index.html'),
            inject: true
        }) ]
};
module.exports  = webpackConf;

(6)在根目錄下新建.babelrc檔案,程式碼如下:

{  "presets": ["es2015","stage-2"],  "plugins": ["transform-runtime"],  "comments": false}