安装webpack

  1. npm i webpack webpack-cli -S

1.2.1、项目目录

config.png

1.2.2、 index.js处理css

  1. npm i style-loader css-loader

index.js

  1. //index.js
  2. import './assets/styles/base.css'

1.2.3、 webpack.config.js

  1. const webpack = require('webpack');
  2. const path = require('path')
  3. const config = {
  4. target:"web",
  5. entry:path.join(__dirname,'src/index.js'),
  6. output:{
  7. filename:'bundle.js',
  8. path:path.join(__dirname,'dist')
  9. },
  10. module:{
  11. rules:[
  12. {
  13. test:/\.css$/,
  14. use:[
  15. 'style-loader',
  16. 'css-loader'
  17. ]
  18. }
  19. ]
  20. },
  21. mode:"development"
  22. }
  23. module.exports = config

1.2.4、 配置html-webpack-plugin

给打包文件一个html文件

  1. npm i html-webpack-plugin -S
  1. var HtmlWebpackPlugin = require('html-webpack-plugin');
  2. var path = require('path');
  3. module.exports = {
  4. entry: 'index.js',
  5. output: {
  6. path: path.resolve(__dirname, './dist'),
  7. filename: 'index_bundle.js'
  8. },
  9. plugins: [new HtmlWebpackPlugin()]
  10. };
  1. npm run build打包
  2. dist文件夹下生产index.html的文件

1.2.5、 清除dist文件夹

在每次构建前清理 /dist 文件夹,这样只会生成用到的文件。让我们实现这个需求。 clean-webpack-plugin 是一个流行的清理插件,安装和配置它。

  1. npm i clean-webpack-plugin -S
  1. const { CleanWebpackPlugin } = require('clean-webpack-plugin');
  2. plugins:[
  3. new CleanWebpackPlugin()
  4. ]