使用webpack4.0 搭建vue环境

851 阅读3分钟

以前都是用vue-cli来进行vue项目的搭建,这次趁周六时间来自己试试用webpack自己搭建vue项目,本文是以webpack4.42.1版本构建的(--save-dev === -D)

1. 创建项目

创建一个文件夹webpack-demo 然后初始化

mkdir webpack-demo
cd webpack-demo
npm init -y //表示npm init -yes 一路默认创建

2. 安装webpack和webpack-cli

这里建议将webpack和webpack-cli安装为本地环境,不要安装为全局环境,因为webpack版本不同有时候会导致项目起不来

npm install webpack webpack-cli --save-dev

此时在项目根目录下新建一个src文件夹和一个webpack.config.js配置文件

webpack-demo
|- src
  |- index.js
|- index.html
|- pageage.json
|- package-lock.json
|- webpack.config.js

index.html

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div id="app">
  </div>
</body>

</html>

webpack.config.js

const path = require('path')


module.exports = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'demo.js',
  },
  devtool: 'inline-source-map', // 构建非常慢但是可以找出源码的错误行数, 可以根据环境去选择各种配置,
  module: {
    
  }
}

3. 安装file-loader babel-loader css-loader style-loader等

npm install -D babel-loader @babel/core @babel/preset-env webpack
npm install -D style-loader css-loader
npm install -D file-loader

webpack.config.js

const path = require('path')


module.exports = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'demo.js',
  },
  devtool: 'inline-source-map', // 构建非常慢但是可以找出源码的错误行数, 可以根据环境去选择各种配置,
  module: {
    rules: [
    + {
    +   test: /.\js$/,
    +    loader: 'babel-loader',
    +    exclude: /node_modules/ //去除modules
    + },
    +  {
    +     test: /.\css$/,
    +      loader: ['style-loader', 'css-loader'] // 从右边往左边读取loader
    +  },
    +  {
    +      test: /.\(jpg|png|svg|gif)$/,
    +      use: [{
    +          loader: 'file-loader'
    +      }]
    +  }
    ]
  }
}

4. 安装html-webpack-plugin 和clean-webpack-plugin插件 安装webpack-dev-server

npm install -D webpack-dev-server
npm install -D html-webpack-plugin
npm install -D clean-webpack-plugin

webpack-dev-server主要本地起个服务器 html-webpack-plugin 主要用来配合html模版自动更新。具体用法请自行google

webpack.config.js

const path = require('path')
+ const HtmlWebpackPlugin = require('html-webpack-plugin')
+ const {
  CleanWebpackPlugin
} = require('clean-webpack-plugin')

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'demo.js',
  },
  devtool: 'inline-source-map', // 构建非常慢但是可以找出源码的错误行数, 可以根据环境去选择各种配置,
  module: {
    rules: [
    {
      test: /.\js$/,
      loader: 'babel-loader',
      exclude: /node_modules/ //去除modules
    },
    {
      test: /.\css$/,
      loader: ['style-loader', 'css-loader'] // 从右边往左边读取loader
    },
    { 
      test: /.\(jpg|png|svg|gif)$/,
      use: [{
        loader: 'file-loader'
     }]
    }
    ]
  },
  plugins: [
    + new HtmlWebpackPlugin({
    +  template: './public/index.html',
    +  hash: true,
    +  title: '你的名字'// 具体作用不太知道有知道的可以评论告诉我
    + }),
    + new CleanWebpackPlugin(),
  ]
}

package.json 添加

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "webpack-dev-server --open --hot"
  },

5. 安装vue相关的loader vue vue-loader vue-template-compiler

npm install vue --save
npm install -D vue-loader vue-template-compiler

webpack.config.js

const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const {
  CleanWebpackPlugin
} = require('clean-webpack-plugin')
+ const VueLoaderPlugin = require('vue-loader/lib/plugin')

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'demo.js',
  },
  devtool: 'inline-source-map', // 构建非常慢但是可以找出源码的错误行数, 可以根据环境去选择各种配置,
  module: {
    rules: [
    {
      test: /.\js$/,
      loader: 'babel-loader',
      exclude: /node_modules/ //去除modules
    },
    {
      test: /.\css$/,
      loader: ['style-loader', 'css-loader'] // 从右边往左边读取loader
    },
    { 
      test: /.\(jpg|png|svg|gif)$/,
      use: [{
        loader: 'file-loader'
     }]
    },
    + {
    +   test: /\.vue$/,
    +   use: [
    +     'vue-loader'
    +   ]
    }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
     template: './public/index.html',
     hash: true,
     title: '你的名字'// 具体作用不太知道有知道的可以评论告诉我
     }),
     new CleanWebpackPlugin(),
    + new VueLoaderPlugin()
  ]
}

6. 试验

基本环境已经搭建完毕下面我们来建一个vue文件来试试 在src目录下新建一个App.vue文件 内容如下

<template>
  <div>
    {{msg}}
    <div class="name">

    </div>
  </div>
</template>
<script>
export default {
  created() {
    this._returnName()
  },
  data () {
    return {
      msg: '我是app2'
    }
  }
  
}
</script>
<style lang="css">
 div {
   color: red;
 }
 .name {
   width: 100px;
   height: 100px;
 }
</style>

在main.js 下内容如下

import Vue from 'vue'
import App from './App.vue'
import './assets/reset/reset.css'
// new Vue({
//   el: '#app',
//   components: { App },
//   template: '<App/>'
// })
new Vue({
  render: h => h(App)
}).$mount('#app')

然后npm run start

现在我们基本实现了vue相关的环境搭建 下面我们来完善一下

图片的加载

  • 我们在src目录下新建文件目录如下 src/assets/img
  • 添加一个名叫logo的图片 我们在App.vue中添加
<template>
  <div>
    {{msg}}
    <div class="name">

    </div>
  </div>
</template>
<script>
export default {
  created() {
    this._returnName()
  },
  data () {
    return {
      msg: '我是app2'
    }
  }
  
}
</script>
<style lang="css">
 div {
   color: red;
 }
 .name {
   width: 100px;
   height: 100px;
   + background: url(./assets/img/logo.png);
 }
</style>

7. 优化

发现我们可以正常使用,但我们npx webpack的时候发现将图片直接打包在dist目录下了这通常不是我们需要的,我们一般用一个文件夹img来放图片 我们更改webpack.config.js中图片配置如下

{
       test: /\.(jpg|png|svg|gif)$/,
       use: [{
         loader: 'file-loader',
          options: {
            name: '[name].[ext]?[hash]',
        +    outputPath: './img'
        }]
      }

这样我们查看name下div发现图片路径为img/logo.png?890.... 我们再在App.vue中添加img标签 发现图片地址变成了[object module] 这是我们在file-loader的配置下添加

{
       test: /\.(jpg|png|svg|gif)$/,
       use: [{
         loader: 'file-loader',
          options: {
            name: '[name].[ext]?[hash]',
        +   outputPath: './img',
        +   esModule: false
        }]
}

此时我们的img标签的src路径就变的正常了。

另外为了路径符合我们习惯我们也可以添加publicPath

{
       test: /\.(jpg|png|svg|gif)$/,
       use: [{
         loader: 'file-loader',
          options: {
            name: '[name].[ext]?[hash]',
        +   outputPath: './img',
        +   publicPath: './img',
        +   esModule: false
        }]
}

此时图片路径为./img/logo.png?9080...

另外webpack也有好多配置可以让我们去配置,此文只做简单的搭建,希望还是要认真看完webpack文档。加深理解。

8. 附录

  • 文件目录如下

  • package.json

  • webpack.config.js