webpack简单配置单页

1.新建目录

1-2.目录结构

webpack简单配置单页

 以红框内的目录结构为主  , 这里没有加入.gitignore  .eslintrc.js  .eslintignore 等文件

package.json内容 

{
  "name": "webpack-dev",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1",
    "build": "webpack",
    "img": "webpack --config webpack.img.js",
    "dev": "webpack-dev-server --config webpack.dev.js",
    "dabao": "webpack --config webpack.prod.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@types/node": "^14.11.5",
    "autoprefixer": "9.8.0",
    "clean-webpack-plugin": "^3.0.0",
    "copy-webpack-plugin": "^6.2.0",
    "css-loader": "^4.3.0",
    "cssnano": "^4.1.10",
    "file-loader": "^6.1.0",
    "glob": "^7.1.6",
    "html-webpack-plugin": "^4.5.0",
    "html-withimg-loader": "^0.1.16",
    "jquery": "^1.11.3",
    "mini-css-extract-plugin": "^0.11.3",
    "postcss-loader": "^4.0.3",
    "postcss-px2rem": "0.3.0",
    "purify-css": "^1.2.5",
    "uglifyjs-webpack-plugin": "^2.2.0",
    "url-loader": "^4.1.0",
    "webpack": "^4.44.2",
    "webpack-dev-server": "^3.11.0",
    "webpack-merge": "^5.2.0",
    "webpack-spritesmith": "^1.1.0",
    "yarn": "^1.22.10"
  },
  "devDependencies": {
    "purgecss-webpack-plugin": "^3.0.0",
    "webpack-cli": "3.3.11"
  }
}

npm install  或者  yarn add *    进行安装

如果有报错 , 那就多装几次

推荐 yarn  安装 . 速度较快 , 且某些依赖下载比较顺畅 , 不会报错

文件中 scripts  对执行文件的命名比较随意 , 可以自行更改 
例如:
npm run build
执行 webpack.config.js
开发环境执行
npm run dev

生产雪碧图
npm run img
项目打包执行
npm run dabao


以下是主要的文件配置

webpack.config.js 内容

const path = require("path");

//Html打包插件
let HtmlWebpackPlugin = require("html-webpack-plugin"); //引入html插件
let glob = require("glob");
//css插件
let PurgecssPlugin = require("purgecss-webpack-plugin"); //清除无用css
let MiniCssExtractPlugin = require("mini-css-extract-plugin"); // CSS抽离插件
// 其他插件
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
let CopyWebpackPlugin = require("copy-webpack-plugin"); //拷贝插件
const webpack = require("webpack");

//模块导出
module.exports = {
  mode: "development",
  entry: path.join(__dirname, "index.js"),
  output: {
    path: path.join(__dirname, "/bundle"),
    filename: "[name].js",
  },
  resolve: {
    //寻找模块规则
    modules: [path.resolve("node_modules")],
    alias: {
      // bootstrap
    },
    extensions: [".ts", ".tsx", ".js", ".css", ".json"],
  },
  // devServer: {
  //   port: 4001,
  //   contentBase: "./bundle",
  //   proxy: {
  //     "/api": {
  //       target: "http://localhost:4001/api",
  //       changeOrigin: true, //解决接口跨域
  //       secure: false, ////https接口需要
  //       pathRewrite: {
  //         "^/api": "",
  //       },
  //     },
  //   },
  // },
  //   watch: true,
  //   watchOptions: {
  //     poll: 1000,
  //     aggregateTimeout: 500,
  //     ignored: /node_modules/,
  //   },
  devtool: "eval-source-map", //映射
  plugins: [
    new HtmlWebpackPlugin({
      template: "./public/index.html",
      filename: "index.html",
    }),
    new webpack.ProvidePlugin({
      $: "jquery",
    }),
    new MiniCssExtractPlugin({
      filename: "css/index.css",
    }),
    new PurgecssPlugin({
      //清除无用css
      paths: glob.sync(`${path.join(__dirname, "/public/*.html")}`, {
        nodir: true,
      }),
    }),
    new CleanWebpackPlugin(),
  ],
  module: {
    rules: [
      {
        test: /.html$/i,
        use: ["html-withimg-loader"],
      },
      // {  //因为在开发环境和生产环境中的资源路径不一 , 所以这里并没有对图片路径做处理 , 所以注释掉了 , 如果两个文件都有对图片处理 , 会报错的
      //   test: /.(png|jpg|gif)$/,
      //   use: [
      //     {
      //       loader: "url-loader",
      //       options: {
      //         limit: 1 * 1024,
      //         outputPath: "./img/",
      //         // publicPath: "https://img.hbhcdn.com/zhuanti/2003469", //资源路径
      //         esModule: false,
      //         name: "[name].[ext]",
      //       },
      //     },
      //   ],
      // },
      {
        test: /.css$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
            options: {
              publicPath: "../", //  在文件路径前加上  './'
            },
          },
          "css-loader",
          "postcss-loader",
        ],
      },
    ],
  },
};

所有打包执行以  webpack.config.js   为主 ,

webpack.dev.js文件内容

let { merge } = require("webpack-merge");
let MiniCssExtractPlugin = require("mini-css-extract-plugin"); // CSS抽离插件
let base = require("./webpack.config.js");
module.exports = merge(base, {
  mode: "development", //开发环境
  devtool: "source-map",
  devServer: {  
    port: 4001,
    contentBase: "./bundle",
    open: true,
    hot: true,
    proxy: {
      "/api": {
        target: "http://localhost:4001/api",
        changeOrigin: true, //解决接口跨域
        secure: false, ////https接口需要
        pathRewrite: {
          "^/api": "",
        },
      },
    },
  },
  module: {
    rules: [
      {
        test: /.(png|jpg|gif)$/,
        use: [
          {
            loader: "url-loader",
            options: {
              limit: 1 * 1024,
              outputPath: "./img/",
              //   publicPath: "https://img.hbhcdn.com/zhuanti/2003469", //资源路径
              esModule: false,
              name: "[name].[ext]",
            },
          },
        ],
      },
    ],
  },
});

这里对资源路径和跨域进行处理

webpack.img.js 内容

//生成雪碧图
var path = require("path");
const SpritesmithPlugin = require("webpack-spritesmith"); //雪碧图
module.exports = {
    mode: "production",
    entry: path.join(__dirname, "sprite.js"),
    plugins: [
        new SpritesmithPlugin({
            src: {
                cwd: path.resolve(__dirname, "./public/icon"),
                glob: "*.png",
            },
            target: {
                image: path.resolve(__dirname, "./public/images/sprite.png"),
                css: path.resolve(__dirname, "./public/css/sprite.css"),
            },
            apiOptions: {
                cssImageRef: "../images/sprite.png",
            },
        }),
    ],
    module: {
        rules: [{
            test: /.png$/,
            use: ["file-loader?name=i/[hash].[ext]"],
        }, ],
    },
    resolve: {
        modules: ["node_modules", "spritesmith-generated"],
    },
};

制作雪碧图

webpack.prod.js 内容  

let {
  merge
} = require("webpack-merge");
let MiniCssExtractPlugin = require("mini-css-extract-plugin"); // CSS抽离插件
let base = require("./webpack.config.js");
module.exports = merge(base, {
  mode: "production", //生产环境
  devtool:false,  
 module: { rules: [{ test:
/.(png|jpg|gif)$/, use: [{ loader: "url-loader", options: { limit: 1 * 1024, outputPath: "./img/", publicPath: "https://img.hbhcdn.com/zhuanti/2005155", //资源路径 esModule: false, name: "[name].[ext]", }, }, ], }, ], }, });

这块比较随意  应该是将beta地址改为 线上地址 , 并打包压缩代码 并设置devtool 为false , 防止线上代码被直接查看

以下是入口文件

因为在webpack.config.js 中将根目录下的  index.js 设为 入口文件所以 ,需要通过es6中的 import 引入对应文件

html文件因为有插件进行打包处理 , 所以不用再这引入

new HtmlWebpackPlugin({
      template: "./public/index.html",
      filename: "index.html",
    }),

index.js内容

import './public/js/index'
import './public/js/px-rem-index'
import "./public/css/sprite.css"
import './public/css/index.css'

webpack.img.js 中 将sprite.js  作为入口文件

sprite.js 里啥也没有 , 只是单单因为必须要有入口文件才能正常打包, 所以强加上的一个文件

其他依赖配置文件

postcss.config.js 内容

module.exports = {
  plugins: [require("autoprefixer"), require('postcss-px2rem')({
    remUnit: 50,
    remPrecision: 2
  })], //配置插件  给css加前缀
};

为css依赖中注入插件,这里是为css添加前缀和rem转换  

只是这还不够

.browserslistrc文件内容

> 1%
last 7 versions,
not ie <= 8,
ios >= 8,
android >= 4.0

为css前缀加入兼容规则

以下是记录下此前写法 :

 之前可以这么玩 ,插件直接写在plugins里 , 很郁闷 ,现在这么写会报错 , 好像有没有plugins这个API了 , 猜想应该是版本更新导致的

{
                test: /.css$/,
                use: [{
                        loader: MiniCssExtractPlugin.loader, //将解析的css抽离为main.css文件
                        options: {
                            publicPath: '../' //这个option必须写,否则css中图片路径可能会出错
                        }
                    },
                    'css-loader', //必须在'css-loader'下面,添加css前缀,配置同级目录下的postcss.config.js文件,进行配置
                    // 'postcss-loader',
                    {
                        loader: 'postcss-loader',
                        options: {
                            plugins: [
                                require('autoprefixer'),
                                //require('cssnano'),<= 需去掉,因为会去掉注释
                                require('postcss-px2rem')({
                                    remUnit: 50,
                                    remPrecision: 2 //精确到多少为小数点后位
                                })
                            ],
                        }
                    }
                ]
            },

最后的最后 , 简简单单的webpack单页就配置完了