webpack搭建vue项目零基础搭建

webpack搭建vue项目步骤详解

自己在搭建vue是遇到很多问题也查啦很多,摸索着搭建完成,在博客记录一下同时加强记忆。

初始化package.json文件

1.创建文件夹,打开cmd命令窗口,执行npm init 命令 初始化package.json文件

 {
    "name": "demo1", 
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1"
    },
    "author": "",
    "license": "ISC"
  }
name表示项目的名称
version表示项目的版本号
description对项目的描述
main项目的入口文件
script脚本命令配置
author作者(可以使用项目作者的名字)
license证书

安装wbepack打包工具和wnepack脚手架

1.执行yarn add webpack webpack——cli --save-dev 或者执行 cnpm/npm install webpack webpack-cli --save-dev

  • 第一个webpack代表安装打包工具
  • 第二个webpack——cli 表示安装 webpack脚手架

2.配置构建脚本 如下面的build脚本

"scripts": {
  "build": "webpack",
  "test": "echo \"Error: no test specified\" && exit 1"
}
  • 配置完成后可以运行npm run build 命令执行项目构建
  • 这时会报错 can not resolve ./src 这是因为找不到项目的入口文件

解决方法

  • 在项目根木录中创建出src文件夹
  • 然后在src文件夹中新增index.js文件 此时js文件名称不能随意命名
  • 解决完成后再次执行npm run build 命令发现项目中多出一个dist文件夹
  • dist文件夹中有一个压缩过后的js文件 main.js 在该文件中可以找到在src文件夹下的index.js的代码

-此时表示能够成功打包项目但是终端会提示未设置mode的警告

  • 现在需要配置package.json中的脚本如下
  • 再次运行npm run build 命令 发现警告消失
  • 运行build脚本生成的js文件会进行压缩 运行dev命令不会
"scripts": {
    "build": "webpack --mode production",
    "dev": "webpack --mode development",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  • production mode(生产模式) 可以开箱即用地进行各种优化。 包括压缩,作用域提升,tree-shaking 等。
  • 另一方面,development mode(开发模式) 针对速度进行了优化,仅仅提供了一种不压缩的 bundle
  • 在 webpack4 中,可以在没有一行配置的情况下完成任务! 只需定义 –mode 参数即可获得所有内容!

配置出入口文件

1.在项目根目录中创建sr文件夹 然后在src文件下创建main.js

  • 这时打包cmd窗口运行 npm run build 命令会报错 因为没有修改入口配置文件配置
    2.这时在项目根目录中创建webpack.config.js文件
  • 在文件里写入
  const path = require('path')
  module.exports = {
    // 配置入口文件 入口的值可以是一个字符串 也可以是一个对象
    // entry: './src/main.js'
    entry: {
      // 入口文件是对象的时候 对象的key(在不配置output的时候)会作为默认生成的js文件的文件名称
      index: './src/main.js'// 需要打包的文件入口   key = index
    },
    // 打包输出文件的相关配置
    // publicPath : __dirname + '/static/' 表示publicpath(资源引入路径)为绝对路径
    // publicPath: '/' 资源引入从根目录开始
    // publicPath: './' 代表相对路径
    //  __dirname:代表当前文件夹
    output: {
      publicPath: '/', // 公共资源引入的路径   // js 引用的路径或者 CDN 地址
      path: path.resolve(__dirname, 'dist'), // 将打包生成的文件夹解析到当前项目的跟目录中   // 打包文件的输出目录
      filename: 'index.js' // 打包生成的js文件的名称     
    }
  }

引入bable (适配为啦让代码在各个浏览器流畅执行)

1.使用 npm i @babel/core babel-loader @babel/preset-env @babel/plugin-transform-runtime @babel/polyfill @babel/runtime --save-dev 输入cmd安装babel相关依赖
2.安装的同时在项目的根目录中创建名为 .babelrc 的新文件来配置 Babel:

{
  "presets": ["@babel/preset-env"],
  "plugins": ["@babel/plugin-transform-runtime"]
}
  • 如果遇运行时到如下警告
WARNING: We noticed you're using the `useBuiltIns` option without declaring a core-js version.
 Currently, we assume version 2.x when no version is passed. 
 Since this default version will likely change in future versions of Babel,
 we recommend explicitly setting the core-js version you are using via the `corejs` option. 
 
You should also be sure that the version you pass to the `corejs` option matches the version specified in your `package.json`
's `dependencies` section. If it doesn't, you need to run one of the following commands: 
 
  npm install --save core-js@2    npm install --save core-js@3 
  yarn add core-js@2              yarn add core-js@3

- 这时候就不仅仅不仅仅要安装 npm install --save core-js@3 还需要设置 .babelrc 设置 “corejs”: 3

{
 "presets": [
   [
     "@babel/preset-env",
     {
       "useBuiltIns": "usage",
       "corejs": 3
     }
   ]
 ],
 "plugins": ["@babel/plugin-transform-runtime"]
}

3.等安装结束后webpack 配置 loader(加载器)

// 在webpack.config.js中添加配置
module: {
  rules: [
    {
      test: /\.js$/, // 使用正则来匹配 js 文件
      exclude: /node_modules/, // 排除依赖包文件夹  //告诉系统那个文件不使用bable依赖 不进行转义
      use: {
        loader: 'babel-loader' // 使用 babel-loader  //告诉系统使用那个loader  
      }
    }
  ]
}

自动生成 HTML 文件

为什么要自动生成HTML 文件那,因为每次要去更改 index.html 中引入 js 文件很麻烦,一旦打包的名字变更后,也要对应的去修改 index.html 引入的 js 名称,这个时候就要使用一个插件来帮助我们,打包完之后自动生成 HTML 文件,并自动引入打包后的 js 文件

1.安装依赖

  • 安装插件
    clean-webpack-plugin用来删除并重新生成dist文件夹 html-webpack-plugin 为了自动生成html文件
  • 安装命令
    npm i html-webpack-plugin html-loader --save-dev
  • 安装完后package.json 如下:
//有里边这几个配置就可以啦
{
  "scripts": {
    "dev": "webpack --mode development",
    "build": "webpack --mode production"
  },
  "devDependencies": {
    "clean-webpack-plugin": "^2.0.0",
    "html-loader": "^0.5.5",
    "html-webpack-plugin": "^3.2.0",
    "webpack": "^4.29.6",
    "webpack-cli": "^3.2.3"
  },
  "dependencies": {
    "lodash": "^4.17.11"
  }
}

2.更改配置文件

  • 安装文成后完善webpack.config.js如下
//  该文件在webpack项目运行时会自动执行
const path = require('path') // 该模块不用下载可以直接使用

// 引入clean-webpack-plugin 插件 作用是每次打包会删除打包生成的文件夹并从新生成一个
const { CleanWebpackPlugin } = require('clean-webpack-plugin')

// 引入自动生成html文件的插件
const HtmlWebpackPlugin = require('html-webpack-plugin')
  module.exports = {
    entry: {
      index: './src/main.js'
    },
    output: {
      publicPath: '/',   // js 引用的路径或者 CDN 地址
      path: path.resolve(__dirname, 'dist'),   // 打包文件的输出目录
      filename: 'index.js'  // 打包后生产的 js 文件
    },
    plugins: [
      new CleanWebpackPlugin(),
      new HtmlWebpackPlugin ({
        title: '自定义标题',
        minify: {
          removeComments: true, // 打包后移除html文件中的注释
          collapseWhitespace: true, // 打包后移除html文件中的空白符
          minifyCSS: true // 压缩内联css
        },
        filename: 'index.html' // 配置生成的html文件名称
      })
    ],
    module: {
        rules: [
        {
            test: /\.js$/,  // 使用正则来匹配 js 文件
            exclude: '/node_modules/',  // 排除依赖包文件夹
            use: {
            loader: 'babel-loader' // 使用 babel-loader
            }
        },
        {
          test: /\.vue$/, //vue规则
          loader: 'vue-loader'
      }
     ]
    },
  }

3.创建模板文件夹

  • 在根目录中创建模板文件夹 public
    • 在 public 中新建一个文件insex.html ,在其中配置代码如下
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
<!-- 这是模板html文件 -->
  <!-- <div>html文件</div> -->
  <div id="app"></div>
</body>
</html>
  • 然后在 weboack.config.js 中的 plugins 配置 template
plugins: [
    new CleanWebpackPlugin(),
    new HtmlWebpackPlugin({
      title: '自定义标题', //生成的html的标题
      minify: {
        removeComments: true, // 打包后移除html文件中的注释
        collapseWhitespace: true, // 打包后移除html文件中的空白符
        minifyCSS: true // 压缩内联css
      },
      template: './public/index.html', // 生成html文件所需要的模板文件   --------------就是配置这个
      filename: 'index.html' // 配置生成的html文件名称
      
    })
  ],
  • 如果需要打包好的文件标题是自定义的需要修改模板文件
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title><%=htmlWebpackPlugin.options.title %></title>
</head>
<body>
<!-- 这是模板html文件 -->
  <!-- <div>html文件</div> -->
  <div id="app"></div>
</body>
</html>

安装webpack-server(项目自启动)

1.安装依赖

  1. cmd运行安装命令npm i webpack-dev-server --save-dev
  2. 配置启动命令, 在package.json 中配置
 "scripts": {
    "serve": "webpack-dev-server",   //就是添加这个 配置这个
    "build": "webpack --mode production",
    "dev": "webpack --mode development",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  1. 添加相关配置告诉server打开那个文件
  • 在webpack.config.js 中配置devServer
devServer: {
    contentBase: path.join(__dirname, 'dist'),
    port: 3000, // 本地服务器端口号
    hot: true, // 热重载
    overlay: true, // 如果代码出错,会在浏览器页面弹出“浮动层”。类似于 vue-cli 等脚手架
    historyApiFallback: {
      // HTML5 history模式
      rewrites: [{ from: /.*/, to: '/index.html' }]
    }
  }
  • 添加模式配置
  mode: 'development', // 开发模式
  devtool: 'source-map', // 开启调试  //开启调试的作用就是为啦调试的时候让文件的代码能看的懂,就算压缩后也能看懂
  devServer: {
    contentBase: path.join(__dirname, 'dist'),
    port: 3000, // 本地服务器端口号  //可以自定义更改
    hot: true, // 热重载
    overlay: true, // 如果代码出错,会在浏览器页面弹出“浮动层”。类似于 vue-cli 等脚手架
    historyApiFallback: {
      // HTML5 history模式
      rewrites: [{ from: /.*/, to: '/index.html' }]
    }
  }
  • 添加热部署和热重载(为啦代码能实时更新)
    • 引入webpack
const webpack = require('webpack')
  • 配置webpack热部署模块(写在webpack.config.js的plugins中)
    new webpack.HotModuleReplacementPlugin(), // 热部署模块
    new webpack.NamedModulesPlugin(),
  plugins: [
    new CleanWebpackPlugin(),
    new webpack.HotModuleReplacementPlugin(), // 热部署模块
    new webpack.NamedModulesPlugin(),
    new HtmlWebpackPlugin ({
      title: '自定义标题',
      minify: {
        removeComments: true, // 打包后移除html文件中的注释
        collapseWhitespace: true, // 打包后移除html文件中的空白符
        minifyCSS: true // 压缩内联css
      },
      template: './public/index.html', // 生成html文件所需要的模板文件
      filename: 'index.html' // 配置生成的html文件名称
    })
  ],
  • 注意点只要配置文件更改都需要重启项目

安装vue相关依赖 (为啦识别vue文件)

  • cmd运行npm install vue vue-router vue-loader vue-template-compiler --save-dev
  • 在webpack.config.js 上边引入vue插件
const VueLoaderPlugin = require('vue-loader/lib/plugin')
  • 然后在webpack.config.js的plugins中引用
  plugins: [
    new CleanWebpackPlugin(),
    new webpack.HotModuleReplacementPlugin(), // 热部署模块
    new webpack.NamedModulesPlugin(),
    new VueLoaderPlugin(),//引用vue插件
    new HtmlWebpackPlugin ({
      title: '自定义标题',
      minify: {
        removeComments: true, // 打包后移除html文件中的注释
        collapseWhitespace: true, // 打包后移除html文件中的空白符
        minifyCSS: true // 压缩内联css
      },
      template: './public/index.html', // 生成html文件所需要的模板文件
      filename: 'index.html' // 配置生成的html文件名称
    })
  ],
  • 配置vue规则(在webpack.config.js的module)
// 在webpack.config.js中添加配置
   module: {
        rules: [
        {
            test: /\.js$/,  // 使用正则来匹配 js 文件
            exclude: '/node_modules/',  // 排除依赖包文件夹  //告诉系统那个文件不使用bable依赖 不进行转义
            use: {
            loader: 'babel-loader' // 使用 babel-loader //告诉系统使用那个loader  
            }
        },
        {
          test: /\.vue$/, //vue规则
          loader: 'vue-loader' // 使用 vue-loade //告诉系统使用那个loader  
      }
        ]
    },
  • 在根目录的src中新建App.vue(默认渲染文件)配置代码如下
<template>
  <div>
  这是vue
  </div>
</template>
  • 配置main.js(渲染vue)代码如下
import Vue from 'vue'
import App from './App.vue'
new Vue({
  router,
  render: h => h(App)
}).$mount('#app')
  • 在public文件夹的的index.html中设置挂载点(实验一下能否正常运行)
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title><%=htmlWebpackPlugin.options.title %></title>
</head>
<body>
<!-- 这是模板html文件 -->
  <!-- <div>html文件</div> -->
  <div id="app"></div>  //设置挂载点
</body>
</html>

webpack.config.js完整代码

//  该文件在webpack项目运行时会自动执行
const path = require('path') // 该模块不用下载可以直接使用

// 引入clean-webpack-plugin 插件 作用是每次打包会删除打包生成的文件夹并从新生成一个
const { CleanWebpackPlugin } = require('clean-webpack-plugin')

// 引入自动生成html文件的插件
const HtmlWebpackPlugin = require('html-webpack-plugin')

// 引入webpack

const webpack = require('webpack')

//引入vue插件
const VueLoaderPlugin = require('vue-loader/lib/plugin')
// console.log('publicPath:' + __dirname + '/static/')
// console.log('path:' + path.resolve(__dirname, 'static'))
module.exports = {
  entry: {
    app: './src/main.js' // 需要打包的文件入口
  },
  output: {
    publicPath: '/', // js 引用的路径或者 CDN 地址
    path: path.resolve(__dirname, 'dist'), // 打包文件的输出目录
    filename: 'bundle.js' // 打包后生产的 js 文件
  },
  plugins: [
    new CleanWebpackPlugin(),
    new webpack.HotModuleReplacementPlugin(), // 热部署模块
    new webpack.NamedModulesPlugin(),
    new VueLoaderPlugin(),
    new HtmlWebpackPlugin ({
      title: '自定义标题',
      minify: {
        removeComments: true, // 打包后移除html文件中的注释
        collapseWhitespace: true, // 打包后移除html文件中的空白符
        minifyCSS: true // 压缩内联css
      },
      template: './public/index.html', // 生成html文件所需要的模板文件
      filename: 'index.html' // 配置生成的html文件名称
    })
  ],
  // 在webpack.config.js中添加配置
  module: {
        rules: [
        {
            test: /\.js$/,  // 使用正则来匹配 js 文件
            exclude: '/node_modules/',  // 排除依赖包文件夹  //告诉系统那个文件不使用bable依赖 不进行转义
            use: {
            loader: 'babel-loader' // 使用 babel-loader //告诉系统使用那个loader  
            }
        },
        {
          test: /\.vue$/, //vue规则
          loader: 'vue-loader' // 使用 vue-loade //告诉系统使用那个loader  
      }
        ]
    },
  mode: 'development', // 开发模式
  devtool: 'source-map', // 开启调试
  devServer: {
    contentBase: path.join(__dirname, 'dist'),
    port: 3000, // 本地服务器端口号
    hot: true, // 热重载
    overlay: true, // 如果代码出错,会在浏览器页面弹出“浮动层”。类似于 vue-cli 等脚手架
    historyApiFallback: {
      // HTML5 history模式
      rewrites: [{ from: /.*/, to: '/index.html' }]
    }
  }
}

  • 运行npm run serve看项目是否能正常运行

完善vue结构

  • 在src中新建文件夹views
    • 新建 Home.vue文件配置如下
<template>
  <div class="home">
    这是home页面
  </div>
</template>
  • 在src中新建文件夹components
  • 在src中新建文件夹router
    • 新建主路由文件index.js配置如下
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
Vue.use(VueRouter)
const routes = [
  {
    path: '/',
    name: 'home',
    component: Home
  }
]

let router = new VueRouter({
  routes
})

export default router
  • 然后在main.js中引入
import Vue from 'vue'
import router from './router/index'
import App from './App.vue'
new Vue ({
    el:'#app',
    router,
    render: h=>h(App)
})
  • 在App.vue中加上路由使其显示默认页面
<template>
  <div id="app">
    <router-view></router-view>
  </div>
</template>

这样就完成啦一个vue项目的搭建 =。=

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值