🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[TOC] [官方文档](https://www.webpackjs.com) # 0.配置前的准备 * 使用webpack必须安装node.js环境; ## npm安装太慢可以安装cnpm,走淘宝的仓库 ``` npm install -g cnpm --registry=https://registry.npm.taobao.org ``` # 1.webpack环境配置 先建一个 src / index.js 文件 ``` npm init -y npm i webpack webpack-cli -g npm i webpack webpack-cli --save-dev //打包 再建一个webpack.config.js webpack ``` ![](https://box.kancloud.cn/e3fbc0f4c29be2b910c153340c81f62d_1920x1080.png) ![](https://box.kancloud.cn/0fa3e5b9617095ee53c5bf679398e76f_1920x1080.png) ``` 如果以上步骤都走了,还是没有dist文件生成 重新走一遍 npm i webpack-cli -g webpack ``` ## plugins(插件) ``` const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); // 通过 npm 安装 const webpack = require('webpack'); // 用于访问内置插件 module.exports = { entry: './src/index.js', output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.js' }, plugins: [ new HtmlWebpackPlugin() ] }; ``` # 2.html-webpack-plugin ## 2.1安装 ``` npm i html-webpack-plugin --save-dev ``` ## 2.2引入 在webpack.config.js文件中 ``` //webpack.config.js const htmlWebpackPlugin = require('html-webpack-plugin') ``` ## 1.3 使用 ``` //webpack.config.js const path = require('path'); const htmlWebpackPlugin = require('html-webpack-plugin');//++ module.exports = { entry: './src/index.js', output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.js' }, //在plugins中使用++ plugins:[ new htmlWebpackPlugin({ title:"打包文件", inject:"head" }) ] }; ``` # 3.clean-webpack-plugin ## 3.1安装 ``` npm i clean-webpack-plugin --save-dev ``` ##3.2使用 ``` //webpack.config.js const path = require('path'); const htmlWebpackPlugin = require('html-webpack-plugin'); const cleanWebpackPlugin = require('clean-webpack-plugin'); //++ module.exports = { entry: './src/index.js', output: { path: path.resolve(__dirname, 'dist'), filename: '[hash].bundle.js' }, plugins:[ new cleanWebpackPlugin(['dist']), //++ new htmlWebpackPlugin({ title:"打包文件", inject:"head", template:"index.html", filename:'[hash]-index.html' }) ] }; ``` # 4. style-loader,css-loader ``` npm i style-loader css-loader --save-dev ``` ``` module: { //允许在js中引入css文件 rules: [{ test: /\.css$/, use: [{ loader: 'style-loader' }, { loader: 'css-loader', options: { modules: true } } ] }] } ``` > 在入口的js中引入css