- 在本地创建项目目录(如d:/webpack-test/);
- 命令行下依次执行以下命令:
1 npm init 2 npm install --save-dev webpack 3 npm install --save-dev webpack-cli 4 npm install --save-dev webpack-dev-server 5 npm install --save-dev html-webpack-plugin
说明:
- webpack-dev-server:webpack的http服务;
- webpack-cli:webpack-dev-server的依赖;
- html-webpack-plugin:打包html的插件;
- 修改项目根目录下文件“package.json”中“scripts”配置项中的“server”:
1 "scripts": { 2 "server": "webpack-dev-server" 3 }
- 在项目目录(d:/webpack-test/)创建另外两个目录“src”,“dist”。
- src 存放源文件;
- dist 存放打包生成的文件;
- 在项目目录下(d:/webpack-test/)建立文件“webpack.config.js”,内容如下:
1 const path = require('path'); 2 const HtmlPlugin = require('html-webpack-plugin'); 3 4 module.exports = { 5 mode: "development", 6 entry: { 7 main: './src/main.js' 8 }, 9 output: { 10 path: path.resolve(__dirname, 'dist'), 11 filename: '[name].js' 12 }, 13 module: { 14 }, 15 plugins: [ 16 //html插件-用于 17 new HtmlPlugin({ 18 minify: { 19 removeAttributeQuotes: true 20 }, 21 hash: true, 22 template: './src/index.html' 23 }) 24 ], 25 devServer: { 26 contentBase: path.resolve(__dirname, 'dist'), 27 host: '10.1.1.179', //本机IP 28 compress: true, 29 port: 9090 30 } 31 };
- 在项目目录下(d:/webpack-test/src)建立文件“index.html”,内容如下:
1 <!DOCTYPE html> 2 <html lang="zh_CN"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 <meta http-equiv="X-UA-Compatible" content="ie=edge"> 7 <title>webpack test</title> 8 </head> 9 <body> 10 <div id="title"></div> 11 </body> 12 </html>
- 在项目目录下(d:/webpack-test/src)建立文件“main.js”,内容如下:
document.getElementById("title").innerHTML = "Hello Webpack.";
- 打包。命令行下依次执行以下命令:
d:
cd d:/webpack-test
webpack
- 在浏览器中浏览网页。
//将10.1.1.179 替换为webpack.config.js中设置的host,9090 替换为webpack.config.js中设置的port
http://10.1.1.179:9090