安装:
npm i clean-webpack-plugin copy-webpack-plugin --save-devjavascript
webpack配置:前端
const CleanWebpackPlugin = require('clean-webpack-plugin') const CopyWebpackPlugin = require('copy-webpack-plugin') const webpack = require('webpack') module.exports = { entry: './src/index.js', output: { filename: 'app.js', path: path.resolve(__dirname, 'dist') }, plugins: [ new CleanWebpackPlugin('./dist'), // 也就是 output.path对应的目录, 相对路径 new CopyWebpackPlugin([ { from: './doc', // 从哪一个文件夹copy内容 to: './' // copy到哪里, 默认为输出目录 } ]), new webpack.BannerPlugin('⌚author: qiqingfu'), // 会将这段内容插入到打包后的js文件最前面 ] }
webpack 能够监听文件变化, 当它们从新修改后会从新编译。
启用 watch
模式, 它是一个 boolean类型的值, 默认为 false。当设置为 true, webpack将监放任何已解析文件的更改。
也可使用 watchOptions
来配置watch模式的选项。java
module.exports = { // watch: true, 开启监听文件变化 watchOptions: { aggregateTimeout: 1000, // 节流, 你这个文件修改后的一秒后,再进行构建 poll: 1000, // 每秒检查一次变更 ignored: /node_modules/ // 排除node_modules,监听大量文件系统会占用更多的CPU和内容消耗 } }
所谓同源是指,域名,协议,端口相同。任何一者不一样都会产生跨域。node
假如:
前端服务为 http: //localhost:8080
后端的连调服务器为: http://192.163.21.1:8082
webpack
前端请求后端提供的接口, 因为域名
和端口
不一样。所产生跨域的现象。git
除了别的解决跨域的方式之外, 在webpack中也能够解决跨域的问题。github
webpack.proxy 启用代理服务器。web
webpack 中的钩子函数中本身mock数据express
在服务端启用 webpacknpm
后端服务: http://localhost:3000
const express = require('express') const app = express() app.get('/qy/user', (req, res) => { console.log(req.url) res.json({ name: 'qiqingfu', age: 21, job: 'web', city: 'QingDao' }) }) app.listen(3000,'localhost', () => { console.warn('port open success: 3000') })
前端请求:
xhr.open('GET', '/api/qy/user', true) xhr.onload = function () { console.log(xhr.response) } xhr.send()
webpack配置proxy代理
devServer: { contentBase: './dist', progress: true, compress: true, port: 8080, proxy: { '/api': { target: 'http://localhost:3000', pathRewrite: {"^/api": ""} // 将/api重写为""空字符串 } } }
凡是接口以 /api
开头的请求,都将其代理到后端的服务器上。http://localhost:3000
。
pathRewrite: {"^/api": ""}, 再将 /api
重写掉。什么意思呢? 由于后端的接口为 /qy/user
,咱们用 /api开头只是为了统一管理, 若是不把/api重写掉,那发给后端的请求是 /api/qy/user
,和后端的接口不匹配。会出问题的。
webpack配置
before: 提供在服务器内部全部其余中间件以前执行自定义中间件的能力
devServer: { contentBase: './dist', progress: true, compress: true, port: 8080, before: app => { app.get('/api/qy/user', (req, res) => { res.json({name: 'mock'}) }) } }
须要weebpack插件: webpack-dev-middleware
server端配置:
const express = require('express') const app = express() const middle = require('webpack-dev-middleware') const webpack = require('webpack') const config = require('./webpack.config') const comiler = webpack(config) app.use(middle(comiler)) app.get('/qy/user', (req, res) => { res.json({ name: 'qiqingfu', age: 21, job: 'web', city: 'QingDao' }) }) app.listen(3000,'localhost', () => { console.warn('port open success: 3000') })
而后启动服务的时候会后续启动 webpack, 直接访问 http://localhost:3000
, 可直接访问到数据