express webpack 项目示例
时间: 2023-11-28 10:41:03 浏览: 37
以下是一个基于 Express 和 Webpack 的项目示例:
1. 首先,创建一个新的目录并初始化 npm:
```
mkdir my-project
cd my-project
npm init -y
```
2. 安装 Express 和相关依赖:
```
npm install express body-parser cors
```
3. 安装 Webpack 和相关依赖:
```
npm install webpack webpack-cli webpack-dev-middleware webpack-hot-middleware html-webpack-plugin
```
4. 创建一个 `src` 目录,并在其中创建一个 `index.js` 文件,作为 Express 应用的入口点:
```javascript
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
app.use(bodyParser.json());
app.use(cors());
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.listen(3000, () => {
console.log('Server listening on port 3000');
});
```
5. 创建一个 `webpack.config.js` 文件,配置 Webpack:
```javascript
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
mode: 'development',
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
},
devServer: {
contentBase: './dist',
hot: true,
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html',
}),
],
};
```
6. 创建一个 `src/index.html` 文件,作为应用的 HTML 模板:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>My App</title>
</head>
<body>
<div id="root"></div>
<script src="bundle.js"></script>
</body>
</html>
```
7. 在 `package.json` 中添加以下脚本:
```json
{
"scripts": {
"start": "webpack-dev-server --open",
"build": "webpack"
}
}
```
8. 运行应用:
```
npm start
```
现在,你可以在浏览器中访问 http://localhost:8080,看到 "Hello, World!" 的输出。