15-webpack学习-使用resolve设置解析路径

本文详细介绍了Webpack的基本配置方法及使用流程,包括项目结构搭建、依赖安装、配置文件编写等核心内容,并提供了实际的打包命令及结果展示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

项目结构
webpackResolve
│  package-lock.json
│  package.json
│  webpack.config.js
└─assets
│   index.css
└─static
│   icon.png
└─src
        index.js

安装依赖

在webpackResolve目录下运行

npm i webpack webpack-cli html-webpack-plugin css-loader style-loader --save-dev
webpack.config.js配置文件
import { resolve } from 'path';
import HtmlWebpackPlugin from 'html-webpack-plugin';
module.exports = {
	mode:'development',
	context:resolve(__dirname,'src'),
	entry:'./index.build.js',
	output:{
		filename:'index.js',
		path:resolve(__dirname,'dist')
	},
	module:{
		rules:[
			{
				test:/\.png$/g,
				use:'asset'
			}
		]
	},
	resolve:{
		alias:{
			assets:resolve(__dirname,'assets'),
			static:resolve(__diranme,'static')
		}
	},
	plugins:[new HtmlWebpackPlugin()]
}

index.js

import 'assets/index.css';
import icon from 'static/icon.png';
// 其他业务逻辑

webpack在解析路径的时候对解析的路径进行匹配,
index.js中assets实际上会被解析成path.resolve(__dirname,‘asstes’) + ‘/index.css’,
而同理icon会被解析成path.resolve(__dirname,‘static’)+‘/icon.png’
与在index.js中使用相对路径或绝对路径加载的路径是一致的;
需要注意的是,alias中的属性尾部不要加$ 符,加上$ 符解析的规则则会变成精准匹配,可以参考文档中的规则

打包命令

  • 方式一:在webpackResolve目录下运行
webpack --config ./webapck.config.js
  • 方式二:在package.json文件的scripts属性新增如下命令
{
	...
	"scripts":{
		"build":"webpack --config ./webpack.config.js"
	}
	...
}

修改保存后,在webpackResolve目录下运行如下命令:

npm run build

打包后的目录

webpackResolve
│  package-lock.json
│  package.json
│  webpack.config.js
├─dist
│      index.build.js
│      index.html
└─assets
│   index.css
└─static
│   icon.png
└─src
        index.js
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值