webpack 是一个前端工程化打包工具,对于前端工程师来讲 webpack 是一项十分重要的技能。下面咱们就经过搭建一个 vue 项目来学习使用 webpackjavascript
主要环境:css
本项目实现如下功能:html
vue/cli
相似的基本目录*.vue
,*.css
等文件es6
及以上语法执行npm init
并建立如下目录前端
demo ├─ dist ├─ public └─ src
npm install -D webpack webpack-cli
npm install -D webpack-dev-server
npm install -D html-webpack-plugin
npm install -D vue-loader vue-template-compiler
npm install -D css-loader style-loader
npm install -D file-loader url-loader
npm install -D @babel/core @babel/cli @babel/preset-env babel-loader
, npm install @babel/polyfill
npm install vue vue-router
新建src/main.js
,并写入:vue
console.log('Hello Webpack');
根目录下新建webpack.config.js
,并写入:java
const path = require('path'); const config = { entry: './src/main.js', // 定义入口文件 output: { path: path.resolve(__dirname + '/dist'), // 打包生成文件地址,必须是绝对路径 filename: '[name].build.js', // 生成的文件名 }, }; module.exports = config;
在package.json
中的scripts
中添加一个脚本:node
{ ... "scripts": { "build": "webpack --mode=production" } ... }
在命令行中执行npm run build
,此时项目目录中出现了dist/main.build.js
,证实执行成功webpack
js 文件打包成功后,须要一个 html 文件来引入这个 js 文件,这就须要用到咱们一开始下载的html-webpack-plugin
git
首先新建public/index.html
建立一个基础页面:es6
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>webpack搭建vue</title> </head> <body> <!-- 若是浏览器禁止加载js脚本 --> <noscript> <strong> We're sorry but this site doesn't work properly without JavaScript enabled. Please enable it to continue. </strong> </noscript> <div id="app"></div> <!-- build后的文件会在这以后自动引入 --> </body> </html>
在public
下随便放入一个图标favicon.ico
,而后在webpack.config.js
中配置插件:
const HtmlWebpackPlugin = require('html-webpack-plugin'); const config = { ... plugins:[ new HtmlWebpackPlugin({ filename: 'index.html', // 生成的文件夹名 template: 'public/index.html', // 模板html favicon: 'public/favicon.ico', // 图标 }), ] } ...
以后再次执行npm run build
,dist
下会生成index.html
,favicon.ico
,main.build.js
三个文件,经过浏览器打开index.html
,就能够发现控制台输出了Hello Webpack
,页面图标也变成了本身设定的图标,经过编辑器打开index.html
,咱们会发现 webpack 帮助咱们自动引入了favicon.ico
和main.build.js
:
<!DOCTYPE html> <html> <head> ... <link rel="icon" href="favicon.ico" /> </head> <body> ... <script src="main.build.js"></script> </body> </html>
webpack 热加载须要用到webpack-dev-server
,在开始咱们已经安装过了,在webpack.config.js
中配置:
const config = { ... devServer: { contentBase: path.join(__dirname, 'dist'), // html所在路径 compress: true, // 是否压缩 port: 3000, // 端口 hot: true, // 热部署 open: true, // 打包完成后自动打开网页 } }
增长package.json
脚本:
{ ... "scripts": { "build": "webpack --mode=production", "serve": "webpack serve" } ... }
执行npm run serve
,打包成功后会自动打开网页,而且当你修改src/main.js
或src/index.html
的内容的时候,浏览器会自动从新打包并刷新
让 webpack 打包*.vue
文件须要vue-loader
和vue-template-compiler
,同时为了 webpack 可以解析 vue 中的 css 还须要用到css-loader
和vue-style-loader
,在webpack.config.js
配置以上插件:
... const { VueLoaderPlugin } = require('vue-loader'); const config = { ... // loaders module: { rules: [ { // *.vue test: /\.vue$/, loader: 'vue-loader', }, { // `*.vue` 文件中的 `<style>` 块以及普通的`*.css` test: /\.css$/, use: ['vue-style-loader', 'css-loader'], }, ], }, plugins: [ ... new VueLoaderPlugin(), ], ... }; ...
配置完后新建src/App.vue
:
<template> <div class="example"> {{ msg }} </div> </template> <script> export default { data() { return { msg: 'Hello Webpack', }; }, }; </script> <style> .example { color: red; } </style>
修改src/main.js
:
import Vue from 'vue'; import App from './App.vue'; new Vue({ el: '#app', render: (h) => h(App), });
而后运行npm run serve
,便可看到页面上显示的Hello Webpack
使用file-loader
或url-loader
加载,它们都是用于打包文件和图片资源的,区别在于url-loader
封装了file-loader
在访问网站时若是图片较多,会发不少 http 请求,会下降页面性能。这个问题能够经过 url-loader
解决。url-loader
会将引入的图片编码,生成 dataURl。至关于把图片数据翻译成一串字符,再把这串字符打包到文件中,最终只须要引入这个文件就能访问图片了。
固然,若是图片较大,编码会消耗性能。所以 url-loader
提供了一个 limit 参数,小于 limit 字节的文件会被转为 DataURl,大于 limit 的还会使用 file-loader 进行 copy。
此处咱们使用 url-loader
,因为它是基于 file-loader
的封装,因此也须要引入 file-loader
。
... const config = { ... module: { rules: [ ... { // 图片 test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, use: { loader: 'url-loader', options: { limit: 25000, }, }, }, ], }, }; ...
而后添加一个图片src/assets/logo.png
,在App.vue
中引入:
<template> <div class="example"> {{ msg }} <img :src="url" /> </div> </template> <script> import logo from './assets/logo.png'; export default { data() { return { msg: 'Hello Vue1', url: logo, }; }, }; </script> <style> .example { color: red; } </style>
再次npm run serve
便可看到图片
babel 能够将 js 的高版本(es6)语法转换为低版本,使得项目兼容低版本浏览器
须要咱们注意的是,babel7 与 babel6 不兼容,所以须要使用最新版本的 babel 和 babel 插件,在前面文章开始咱们已经安装了 babel7 版本的 babel 插件,下面咱们在webpack.config.js
中配置它:
... const config = { ... module: { rules: [ ... { // *.js test: /\.js$/, exclude: /node_modules/, // 不编译node_modules下的文件 loader: 'babel-loader', }, ], }, }; ...
配置完后在项目根目录下建立一个 babel 的配置文件.babelrc
,写入以下内容:
{ "presets": [ [ "@babel/preset-env", { "useBuiltIns": "entry" } ] ] }
更多 babel 配置请查看babel 中文官网
配置完成后新建一个src/utils/getData.js
测试一下:
export default function getData() { return new Promise((resolve, reject) => { resolve('ok'); }); }
在src/App.vue
中引入:
<template> <div class="example"> {{ msg }} <img :src="url" /> </div> </template> <script> import logo from './assets/logo.png'; import getData from './utils/getData'; export default { data() { return { msg: 'Hello Vue1', url: logo, }; }, methods: { async fetchData() { const data = await getData(); this.msg = data; }, }, created() { this.fetchData(); }, }; </script> <style> .example { color: red; } </style>
从新执行npm run serve
后,页面显示ok
,babel 引入成功
为了方便开发,咱们能够给 src 目录设置别名,以及将经常使用文件类型的后缀省略
... const config = { ... // 解析路径 resolve: { // 设置src别名 alias: { '@': path.resolve(__dirname, 'src'), }, //后缀名 能够根据须要自由增减 extensions: ['.js', '.vue'], }, ... }; ...
这样咱们就能够以以下方式导入 vue 和 js 文件:
// 导入App.vue import App from '@/App'; // 导入getData import getData from '@/utils/getData';
至此,咱们已经简单的搭建出了 vue 项目,在项目中咱们可能还会须要用到less
,sass
,字体图标等工具,针对这类工具 webpack 都有与其对应的loader
或plugin
,须要时搜索他们的文档便可。