1. 程式人生 > >VUE+Webpack搭建開發環境

VUE+Webpack搭建開發環境

專案地址:https://github.com/zhongjunyao/VUE-Webpack.git

1.首先開啟開發工具 Visual Studio Code ,將資料夾新增到專案,可以看到資料夾VUE-Webpack已經新增到專案中了

從控制檯中進入資料夾 VUE-Webpack 中,執行 命令 npm init

PS D:\workspace\VUE-Webpack> npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (vue-webpack)
version: (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to D:\workspace\VUE-Webpack\package.json:

{
  "name": "vue-webpack",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}


Is this ok? (yes)
PS D:\workspace\VUE-Webpack> npm i vue vue-loader css-loader  webpack --save-dev
npm WARN rollback Rolling back 
[email protected]
failed (this is probably harmless): EPERM: operation not permitted, scandir 'D:\workspace\VUE-Webpack\node_modules\fsevents' npm notice created a lockfile as package-lock.json. You should commit this file. npm WARN [email protected] No description npm WARN [email protected]
No repository field. npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\fsevents): npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"}) + [email protected]
+ [email protected] + [email protected] + [email protected] added 368 packages in 51.432s PS D:\workspace\VUE-Webpack>

安裝一下vue-template-compiler

PS D:\workspace\VUE-Webpack> npm i vue-template-compiler --save-dev
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): EPERM: operation not permitted, scandir 'D:\workspace\VUE-Webpack\node_modules\fsevents'
npm WARN [email protected] No description
npm WARN [email protected] No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

+ [email protected]
added 3 packages in 7.146s
PS D:\workspace\VUE-Webpack>

新建目錄src,建立如圖檔案內容

此處我們使用了stylus,所以需要安裝 stylus 的相關檔案,另外我們還需要給一些css屬性加上字首,-webkit- 等,所以也要安裝 postcss、autoprefixer

PS D:\workspace\VUE-Webpack> npm i stylus stylus-loader postcss --save-dev
npm WARN [email protected] No description
npm WARN [email protected] No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

+ [email protected]
+ [email protected]
+ [email protected]
added 38 packages and updated 1 package in 10.856s
PS D:\workspace\VUE-Webpack> npm i autoprefixer --save-dev
npm WARN [email protected] No description
npm WARN [email protected] No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

+ [email protected]
added 8 packages in 9.29s
PS D:\workspace\VUE-Webpack>

 

此外由於需要使用到 jsx 語法 和 ES6語法 等 ,需要安裝 babel-plugin-syntax-jsx 、babel-loader、babel-core

PS D:\workspace\VUE-Webpack> npm i babel-plugin-syntax-jsx babel-core babel-loader --save-dev
npm WARN [email protected].4 requires a peer of @babel/[email protected]^7.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] No description
npm WARN [email protected] No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

+ [email protected]
+ [email protected]
+ [email protected]
added 54 packages in 22.086s
PS D:\workspace\VUE-Webpack>

接下來我們需要配置三個檔案.babelrc,postcss.config.js,webpack.config.js,在這個過程中我們可能需要用到其他的檔案,遇到 再安裝。

.babelrc檔案

{
  "presets":[
    "env"
  ],
  "plugins":[
    "transform-vue-jsx"
  ]
}

postcss.config.js

const autoprefixer = require('autoprefixer');

module.exports = {
  plugins: {
    'autoprefixer': {browsers: 'last 6 version'}
  }
}

webpack.config.js

// webpack 用於打包專案的資源
const VueLoaderPlugin = require('vue-loader/lib/plugin');
// 引入html-webpack-plugin
const HTMLPlugin = require('html-webpack-plugin')
const webpack = require('webpack')
// ExtractPlugin 將非html的資源作為單獨的檔案打包出來
const ExtractPlugin = require('extract-text-webpack-plugin')
const path = require('path');// 獲取當前路徑物件
const isDev = process.env.NODE_ENV === 'development'

const config = {
  
  // 1.宣告入口路徑 使用絕對路徑
  // __dirname 是當前檔案路徑,即根目錄
  // join函式將2個引數拼接為一個
  entry:path.join(__dirname,'src/index.js'),
  // 2.宣告出口路徑 使用絕對路徑
  output:{
    filename:'bundle.[hash:8].js',
    path:path.join(__dirname,'dist')
  },
  // 3.宣告使用到的外掛
  plugins: [
    // 此處新增webpack.DefinePlugin使得其內的變數可以在我們的JS中訪問到
    new webpack.DefinePlugin({
      'process.env':{
        NODE_ENV: isDev ? '"development"' : '"production"'
      }
    }),
    new VueLoaderPlugin(),
    new HTMLPlugin({
      title:"Vue自構建專案",// 生成html檔案的標題
      filename: 'index.html', // 就是html檔案的檔名,預設是index.html
      // template: 'index.html',
      inject: 'body', // script標籤位於html檔案的 body 底部
      // favicon:path.join(__dirname,'src/assets/images/cir_select.png'),
      meta:[
        { name:'viewport', content:'width=device-width, initial-scale=1.0,use-scalable=no' },
        { name:'keywords', content:'vue' },
        { name:'keywords', content:'webpack,構建' }
      ],
    })
  ],
  // 4.聲明當前的模式 '開發' 或者 '生產'
  mode:"development",//'development' or 'production'
  // 5.宣告模組規則,如指定的檔案型別.vue 通過什麼來載入編譯
  module:{
    rules:[
      { test:/\.vue$/, loader:'vue-loader' },
      { test:/\.jsx$/, loader:'babel-loader' },
      // { test: /\.css$/, use: ["style-loader", "css-loader"] },
      { 
        test:/\.(gif|jpg|jepg|png|svg)/,
        use:[
          { 
            loader:'url-loader',
            options:{
              limit:1024,
              name:'[name]-pic.[ext]'
            }
          }
        ]
      }
      
    ]
  },
  // 6.宣告編譯的目標是web平臺
  target:'web'

}
// 7.設定當開發環境時多一個配置項
if(isDev){
  config.devtool = '#cheap-module-eval-source-map'
  config.devServer = {
    port:8000,
    host:'0.0.0.0', // 同個區域網內別人可以訪問你的電腦web頁面,手機也可以訪問
    overlay:{
      errors:true,//編譯過程有任何的錯誤都顯示在網頁上
    },
    // open:true, // 執行dev命令自動開啟頁面
    hot:true,
  }
  config.plugins.push(
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoEmitOnErrorsPlugin()
  )
  config.module.rules.push({ 
    test:/\.styl(us)?$/,
    use:[
      {loader:'style-loader'},
      {loader:'css-loader'},
      {
        loader:'postcss-loader',
        options:{
          sourceMap:true,
        }
      },
      {loader:'stylus-loader'}
    ] 
  })
}else{
  config.entry = {
    app:path.join(__dirname,'src/index.js'),
    vendor:['vue']
  }
  config.output.filename = '[name].[chunkHash:8].js'
  config.module.rules.push({ 
    test:/\.styl(us)?$/,
    use:ExtractPlugin.extract({
      fallback:'style-loader',
      use:[
        'css-loader',
        {
          loader:'postcss-loader',
          options:{
            sourceMap:true,
          }
        },
        'stylus-loader'
      ]
    })
  })
  config.plugins.push(
    new ExtractPlugin('styles.[hash:8].css')
  )
  config.optimization = {
    splitChunks: {
      chunks: 'async',
      minSize: 30000,
      maxSize: 0,
      minChunks: 1,
      maxAsyncRequests: 5,
      maxInitialRequests: 3,
      automaticNameDelimiter: '~',
      name: true,
      cacheGroups: {
        vendors: {
          test: /[\\/]node_modules[\\/]/,
          priority: -10
        },
        default: {
          minChunks: 2,
          priority: -20,
          reuseExistingChunk: true
        }
      }
    }
  }
}

module.exports = config

接下來配置package.json

{
  // ...
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "cross-env NODE_ENV=production webpack --config webpack.config.js",
    "dev": "cross-env NODE_ENV=development webpack-dev-server --config webpack.config.js"
  },
  // ...
}

安裝cross-env

PS D:\workspace\VUE-Webpack> npm i cross-env --save-dev
npm WARN [email protected] requires a peer of @babel/[email protected]^7.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] No description
npm WARN [email protected] No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

+ [email protected]
added 8 packages in 13.14s
PS D:\workspace\VUE-Webpack>

上面有個警告,npm WARN [email protected] requires a peer of @babel/[email protected]^7.0.0 but none is installed. 

我們有兩種解決辦法,一種是babel-loader降版本,一種是提升babel-core的版本為7

先提升babel-core版本

我們發現沒有匹配的的7.0版本,只能將babel-loader降級

PS D:\workspace\VUE-Webpack> npm i cross-env [email protected] --save-dev
npm WARN [email protected] No description
npm WARN [email protected] No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

+ [email protected]
+ [email protected]
removed 13 packages and updated 2 packages in 10.196s
PS D:\workspace\VUE-Webpack>

為了實現開發時的熱過載功能,需要安裝webpack-dev-server

PS D:\workspace\VUE-Webpack> npm i webpack-dev-server --save-dev
npm WARN [email protected] No description
npm WARN [email protected] No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

+ [email protected]
added 165 packages in 30.003s

執行npm run dev 命令,需要安裝webpack -cli

PS D:\workspace\VUE-Webpack> npm i webpack-cli -D
npm WARN [email protected] No description
npm WARN [email protected] No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

+ [email protected]
added 5 packages in 10.869s
PS D:\workspace\VUE-Webpack>

將webpack.config.js中使用到的外掛安裝 

PS D:\workspace\VUE-Webpack> npm i html-webpack-plugin --save-dev
...
+ [email protected]
updated 44 packages in 59.261s

PS D:\workspace\VUE-Webpack> npm i [email protected]^4.0.0-beta.0 --save-dev
// ...
+ [email protected]
removed 4 packages and updated 2 packages in 9.759s

PS D:\workspace\VUE-Webpack> npm i babel-plugin-transform-vue-jsx --save-dev
npm WARN [email protected] requires a peer of [email protected]^2.0.0 but none is installed. You must install peer dependencies yourself.
...
+ [email protected]
added 1 package in 8.734s

PS D:\workspace\VUE-Webpack> npm i style-loader --save-dev
npm WARN [email protected] requires a peer of [email protected]^2.0.0 but none is installed. You must install peer dependencies yourself.
...
+ [email protected]
added 2 packages in 9.029s

PS D:\workspace\VUE-Webpack> npm i postcss-loader babel-helper-vue-jsx-merge-props  --save-dev
...
+ [email protected]
+ [email protected]
added 1 package and updated 1 package in 9.044s

PS D:\workspace\VUE-Webpack> npm i url-loader --save-dev
...
+ [email protected]
added 3 packages in 9.992s

PS D:\workspace\VUE-Webpack> npm i css-loader --save-dev
...
+ [email protected]
updated 1 package in 11.587s

PS D:\workspace\VUE-Webpack> npm i file-loader --save-dev
...
+ [email protected]
added 2 packages in 8.552s

PS D:\workspace\VUE-Webpack> npm i babel-preset-env --save-dev
...
+ [email protected]
added 45 packages in 13.513s

執行npm run dev,在瀏覽器中輸入http://localhost:8000/ 

開發環境配好之後,我們釋出專案還需將專案打包

執行npm run build

打包之後,用瀏覽器開啟index.html檔案