webpack-config
webpack-config
一、config-path
1.config-output-devserver-publicPath
简述:
/**
* output:
* - publicPath: index.html内部的引用路径
* - 域名 + (缺'/'时,浏览器会自动添加)publicPath + filename 本地访问时(不使用dev-server),不用加域名
* - 结论:在本地访问,写''或相对路径,使用dev-server使用''或以'/'开头的绝对路径
*
* devServer:
* static:
* - publicPath(之前在devServer下): 指定本地服务所在的目录(将打包的结果放在指定目录之下)
* 建议将output.publicPath 与 devServer.publicPath 保持一致
* - directory(之前在devServer下,contentPath): 我们打包之后的资源,如果依赖其它资源,就告知去哪里找
* - watch:true 检测资源变化,自动刷新
*/
配置:
module.exports = {
...
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/lg', // 默认值为' '
},
target: 'web',
devServer: {
hot: true,
static: {
publicPath: '/lg',
directory:path.resolve(__dirname,'public'),
watch: true
},
}
}
2.devServer常用配置
devServer: {
compress: true, // 将资源压缩之后,再返回给客户端展示
port: 5505, // 端口
hot: 'only', // 当某个模块错误被纠正时,只会更新单个模块,true时会更新所有模块
open:false, // 是否自动打开浏览器
historyApiFallback: true , // 当使用前端路由请求后端时,如果路由不存在,应该使用前端路由匹配
},
二、proxy代理服务
解决cros跨域请求:
// 常用proxy配置
devServer: {
...
proxy: {
// 匹配'/api'开头的请求,代理到localhost:5500
'/api': {
target: 'https://jsonplaceholder.typicode.com',
changeOrigin: true,
pathRewrite: {
'^/api': '',
},
}
}
},
三、resolve模块解析规则
module.exports = {
...
resolve:{
extensions:['.js','.jsx','.json','.ts','.vue'],
},
}
// 引入模块时,可简写
import About from './components/About'; // About.jsx
配置路径别名:
resolve:{
...
alias:{
'@':path.resolve(__dirname,'src'),
}
},
// 使用别名简化导入模块是的书写路径
import Home from '@/components/Home';
四、dev-tools配置
a.source-map
source-map --> 在调试的时候可以定位到源代码的信息
该模式,会生成.map文件,用于浏览器定位源代码
配置:
mode:'development', // development 会自动开启devtool: 'eval' eval-source-map
// eval-source-map 与 inline-source-map 不同的是,它不会生成一个单独的文件,而是内联到打包后的文件中(dataUrl)
// cheap-source-map 与 cheap-module-source-map
devtool:'source-map'
五、编译TS
a.ts-loader编译ts
只能处理编译ts文件。不能处理一下polyfill一些较新的语法,且可以在编译阶段就发现ts语法错误
安装依赖:
yarn add -D ts-loader typescript
配置loader处理ts文件:
{
test: /\.ts$/,
use: ['ts-loader'],
}
b.使用babel-loader编译ts
完成对polyfill的支持,ts的语法错误,在编译阶段不能发现,在运行阶段才能发现
安装依赖:
yarn add core-js regenerator-runtime // 完成polyfill功能的依赖
yarn add babel-loader @babel/core @babel/preset-typescript //完成ts文件的编译
配置:
// main.ts中引入 polyfill依赖
import 'core-js/stable';
import 'regenerator-runtime/runtime';
// webpack.config.js中配置babel-loader
{
test: /\.ts$/,
exclude: /node_modules/,
use: ['babel-loader'],
}
// 配置babel-loader参数,完成polyfill功能
module.exports = {
presets: [
['@babel/preset-env',{
useBuiltIns: 'usage',
corejs: 3,
}],
['@babel/preset-typescript']
]
}
c.综合
先使用tsc 完成编译阶段的语法检错,再使用babel-loader的编译与polyfill功能
综合性命令完成功能:
"ts_build":"npm run ck && webpack",
"ck":"tsc --noEmit"
六、编译vue
安装依赖:
yarn add -D vue@2.6 vue-loader@15 vue-template-compiler@2.6
配置loader:
const VueLoaderPlugin = require('vue-loader/lib/plugin');
module.exports = {
...
module: {
rules: [
...
{
test: /\.less$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
importLoaders: 2,
esModule: false
}
},
'postcss-loader',
'less-loader'
]
},
{
test: /\.vue$/,
loader: 'vue-loader'
}
]
},
plugins: [
...
new VueLoaderPlugin()
]
}
七、打包环境的区分
分写webpack配置文件
-config
-webpack.common.js
-webpack.dev.js
-webpack.prod.js
启动命令传参:
"scripts": {
"build": "webpack",
"serve": "webpack serve",
"build2": "webpack --config ./config/webpack.common.js --env production",
"serve2": "webpack serve --config ./config/webpack.common.js --env development"
},
路径处理模块:
const path = require('path');
const appDir = process.cwd();
console.log(appDir,'<----- appDir');
module.exports = (relativePath) => path.resolve(appDir, relativePath);
根据参数区分打包环境webpack.common.js:
// webpack.config.js
const resolvePath = require('./paths');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { merge } = require('webpack-merge'); // 合并webpack配置
// 定义对象保存 base 配置
const commonConfig = {
entry: './src/main.js', // 反而没有报错(相对路径)
context: resolvePath('./'), // 当前次打包的上下文 默认是所写的配置文件的路径上下文
output: {
path: resolvePath('./dist'),
filename: 'bundle.js',
},
resolve: {
alias: {
'@': resolvePath('./src')
},
extensions: ['.js', '.json', '.ts', '.jsx', '.vue']
},
module: {
rules: [
{
test: /\.css$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
importLoaders: 1,
esModule: false
}
},
'postcss-loader',
]
},
{
test: /\.less$/,
use: [
'style-loader',
'css-loader',
'postcss-loader',
'less-loader'
]
},
{
test: /\.(png|jpg|gif)$/,
type: 'asset',
generator: {
filename: 'imgs/[name].[hash:4][ext]',
},
parser: {
dataUrlCondition: {
maxSize: 10 * 1024
}
}
},
{
test: /\.(woff2?|eot|ttf|otf)$/,
type: 'asset/resource', // 图标字体文件,只需要拷贝到dist目录即可
generator: {
filename: 'font/[name].[hash:3][ext]'
}
},
{
test: /\.jsx?$/,
exclude: /node_modules/, // 排除掉node_modules目录下的js文件,避免重复填充处理
use: ['babel-loader'],
}
]
},
plugins: [
new HtmlWebpackPlugin({
title: 'babel-webpack-plugin',
template: './public/index.html',
}),
]
}
module.exports = (env) => {
const isProduction = env.production;
console.log(new Boolean(isProduction), '<----- isProduction');
const config = merge(commonConfig, isProduction ? require('./webpack.prod') : require('./webpack.dev'));
return config;
}
生产环境webpack.prod.js(这里会报错,再处理ts的babel-loader中,配置了ts模块刷新):
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
module.exports = {
mode: 'production',
plugins: [
new CleanWebpackPlugin(),
new CopyWebpackPlugin({
patterns: [
{
from: 'public',
// to:'dist', 默认到output目录下
globOptions: {
ignore: ['**/index.html'] // 忽略掉该目录下的index.html文件
}
}
]
}),
]
}
开发环境webpack.dev.js:
const path = require('path');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin')
module.exports = {
mode: 'development',
devtool: 'source-map',
target: 'web', // 开发阶段屏蔽.browserslistrc
devServer: {
compress: true, // 将资源压缩之后,再返回给客户端展示
port: 5505, // 端口
hot: 'only', // 当某个模块错误被纠正时,只会更新单个模块,true时会更新所有模块
open: false, // 是否自动打开浏览器
historyApiFallback: true, // 当使用前端路由请求后端时,如果路由不存在,应该使用前端路由匹配
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
title: 'babel-webpack-plugin',
template: './public/index.html',
}),
new CopyWebpackPlugin({
patterns: [
{
from: 'public',
// to:'dist', 默认到output目录下
globOptions: {
ignore: ['**/index.html'] // 忽略掉该目录下的index.html文件
}
}
]
}),
new ReactRefreshWebpackPlugin(),
]
}
13 声望
1 粉丝
推荐阅读
rollup简易使用
参考原链接:[链接]作者:Alaso来源:稀土掘金rollup安装与使用安装 {代码...} 使用不使用配置文件配置到script中 {代码...} 参数解释-i指定要打包的文件,-i是--input的缩写。src/index.js是-i的参数,即打包入...
小江不可求阅读 563
浅析 SplitChunksPlugin 及代码分割的意义
A: 最初,chunks(以及内部导入的模块)是通过内部webpack 图谱中的父子关系关联的。CommonsChunkPlugin曾被用来避免他们之间的重复依赖,但是不可能再做进一步的优化。从webpack v4 开始,移除了CommonsChunkPlu...
heweixiao赞 2阅读 528
【关于webpack的打包原理】webpackJsonpCallback的学习笔记
代码中的webpackJsonpCallback是什么意思?webpackJsonpCallback是webpack在浏览器端异步加载模块的时候定义的全局函数。当webpack加载一个异步模块时,会生成一个script标签,指向异步模块的url,此时浏览器会异...
梨花赞 1阅读 775
「Webpack5源码」enhanced-resolve路径解析库源码分析
本文内容基于webpack 5.74.0和enhanced-resolve 5.12.0版本进行分析webpack5核心流程专栏共有5篇,使用流程图的形式分析了webpack5的构建原理:「Webpack5源码」make阶段(流程图)分析「Webpack5源码」enhanced-...
白边赞 2阅读 519
前端微服务跨域配置解决办法,devServer为例
前言Nginx: 在上一篇我提到的跨域配置是正式上线的时候使用nginx做为配置的参考。Webpack: 而我们更多的时候是在开发阶段就需要通过跨域进行联合开发各个子应用部分功能DevServer配置解决跨域子应用静态资源跨域...
smallStone赞 2阅读 2.3k评论 12
回顾webpack在vue.config.js中写loader和plugin
我们知道,无论是Vue的vue-cli还是React的create-react-app这样的脚手架,实际上都是给webpack做了一层封装,包了一层壳子,并预设了一些默认常用的配置项(当然还有别的东西),以便提升开发效率。
水冗水孚赞 1阅读 784
webpack关于chunkFilename
相对于output.filename,output.chunkFilename用来配置通过require.ensure加载的模块文件当是cmd和amd异步加载并且没有给入口文件时,可以通过output.chunkFilename来配置命名未被列在entry中,却又需要被打包出...
十只生蚝阅读 1k
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。