🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
新建目录文件 mkdir webpack-test ~~~ npm init npm install webpack webpack-cli -g npm install webpack webpack-cli --save-dev ~~~ 下载lhtml-webpack-plugin插件 ~~~ npm i html-webpack-plugin -D ~~~ **webpack.config.js** 作用:当运行webpack指令时,会自动加载这里面的配置 ~~~ //引入插件 const HtmlWebpackPlugin = require('html-webpack-plugin'); //resolve用来解决绝对路径的 const {resolve} = require('path'); module.exports = { mode:'development',//development和production //打包的入口文件 entry: './src/index.js', output: { //输出路径,__dirname是nodejs的变量代表当前文件的目录绝对路径 path: resolve(__dirname, 'dist'), //打包输出的文件名 filename: 'build.js' }, module: { rules: [ ] }, plugins: [ //html-webpack-plugin默认创建一个空的HTML,自动引入打包输出所有资源(js/css) new HtmlWebpackPlugin(); //如果我们需要src/index.html页面的结构,需要一个template参数复制./src/index.html文件,并自动引入打包输出所有资源(js/css) new HtmlWebpackPlugin({template: './src/index.html'}) ] }; ~~~ src/index.html ``` <!DOCTYPE html> <html lang="zh-cn"> <head> <meta charset="utf-8"> <title>site title</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <h1 id="title">hello world!</h1> </body> </html> ``` src/index.js ~~~ document.write("It works."); ~~~ dist/index.html new HtmlWebpackPlugin();时生成的页面 ``` <!DOCTYPE html> <html lang="zh-cn"> <head> <meta charset="utf-8"> <title>site title</title> </head> <body> <script src="./built.js" type="text/javascript"></script> </body> </html> ``` dist/index.html new HtmlWebpackPlugin({template: './src/index.html'});时生成的页面 ``` <!DOCTYPE html> <html lang="zh-cn"> <head> <meta charset="utf-8"> <title>site title</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <h1 id="title">hello world!</h1> <script src="./built.js" type="text/javascript"></script> </body> </html> ```