Webpack - 基础设置
一:基础设置
参考:https://webpack.js.org/guides/getting-started/
npm init -y
npm install webpack webpack-cli --save-dev
代码:
webpack.config.js
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist'),
},
};
package.json
{
"name": "sample-1",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"webpack": "^5.25.0",
"webpack-cli": "^4.5.0"
}
}
Src/index.js
function component() {
const element = document.createElement('div');
// Lodash, currently included via a script, is required for this line to work
element.innerHTML = 'hello, world!'; //_.join(['Hello', 'webpack'], ' ');
return element;
}
document.body.appendChild(component());
dist/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Getting Started</title>
<script src="https://unpkg.com/lodash@4.17.20"></script>
</head>
<body>
<script src="main.js"></script>
</body>
</html>
最后:npm run build
二:加载CSS
npm install --save-dev style-loader css-loader
webpack.config.js加入以下配置
module: {
rules: [
{
test: /\.css$/i,
use: ['style-loader', 'css-loader'],
},
],
},
增加src/style.css
.hello {
color: red;
}
Index.js增加以下代码
import './style.css';
element.classList.add('hello');
三:加载图片
Webpack.config.js -> Module节点加入以下代码
{
test: /\.(png|svg|jpg|jpeg|gif)$/i,
type: 'asset/resource',
}
Src -> 添加logo.png
Index.js 添加
const myIcon = new Image();
myIcon.src = Icon;
element.appendChild(myIcon);
style.css 添加
background: url('./logo.png');
最后npm run build
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具