webpack的配置

132 阅读2分钟

##准备工作

npm init -y; //生成一个package.json文件,安装的依赖包会保存在此文件中
这里最好使用我的这个package.json文件,以防版本不一样,导致打包失败。
打包命令:webpack
{
  "name": "cart",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "webpack": "webpack --config webpack.config.js",
    "dev": "webpack-dev-server --host localhost --content-base dist/ --hot --config webpack.config.js --progress --display-modules --colors --display-reasons"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "autoprefixer": "^9.5.1",
    "babel-core": "^6.26.3",
    "babel-loader": "^7.1.5",
    "babel-preset-latest": "^6.24.1",
    "css-loader": "^2.1.1",
    "ejs": "^2.6.1",
    "ejs-loader": "^0.3.3",
    "file-loader": "^3.0.1",
    "html-loader": "^0.5.5",
    "html-webpack-plugin": "^3.2.0",
    "image-webpack-loader": "^4.6.0",
    "mini-css-extract-plugin": "^0.7.0",
    "node-sass": "^4.11.0",
    "postcss-loader": "^3.0.0",
    "sass-loader": "^7.1.0",
    "style-loader": "^0.23.1",
    "uglifyjs-webpack-plugin": "^2.1.2",
    "url-loader": "^1.1.2",
    "webpack": "^4.30.0",
    "webpack-cli": "^3.3.0",
    "webpack-dev-server": "^3.7.2"
  }
}

#创建webpack.config.js文件

const path = require('path');
const uglify = require('uglifyjs-webpack-plugin');//用来压缩优化js文件
const htmlWebpackPlugin = require('html-webpack-plugin');//生成创建html入口文件
const autoprefixer = require('autoprefixer');//css兼容性前缀
const MiniCssExtractPlugin = require('mini-css-extract-plugin');//这个插件会单独将css文件提取成一个独立的文件

const config = {
    mode: 'development', //上线的时候需要改成production 生产环境是 production
    // source-map 有利于出错的时候通过断点可以显示原始代码
    devtool: "source-map",
    // 优化,禁止压缩
    optimization: {
        minimize:false
    },
    // 入口文件,多文件需要用对象写法
    entry: {
        // resolve(__dirname) dirname表示当前文件夹下的
        index: path.resolve(__dirname, 'src/js/index.js'),
        detail: path.resolve(__dirname, 'src/js/detail.js'),
        collections: path.resolve(__dirname, 'src/js/collections.js')
    },
    // 输出,打包的设置
    output: {
        // 打包后的路径  和  文件名
        path: path.resolve(__dirname + '/dist'),
        filename: 'js/[name].js'
    },
    // 配置loader
    module: {
       // 模块的匹配规则
        rules: [
        {
            test: /\.js$/,
            loader: 'babel-loader',//es6转es5
            exclude: path.resolve(__dirname, 'node_modules'),//不包含当前路径下的node_modules文件夹
            query: { //通过预设转换代码。就是安装的es6转es5的工具
                'presets': ['latest']
            }
        },
        {
            test: /\.tpl$/,
            loader: 'ejs-loader'
        },
        {
            test: /\.css$/,
            // 多个loader的时候,需要通过use
            use: [
                // {
                //     loader: MiniCssExtractPlugin.loader,
                //     options: {
                //         hmr:process.env.NODE_ENV==='development'
                //     }
                // },
                'style-loader',
                'css-loader',
                {
                    loader: 'postcss-loader',//需配合autoprefixer插件,加兼容性前缀
                    options: {
                        plugins: function () {
                            return [autoprefixer('last 5 versions')] // 兼容最近的5个版本
                        }
                    }
                },
            ]
        },
        {
            test: /\.scss$/,
            use: [
                // { //这个对象文件 是单独把css作为一个文件夹拿出来,如果不希望单独生成一个文件夹,可以使用 style-loader,style-loader打包后会在head标签内引入style标签样式
                //     loader: MiniCssExtractPlugin.loader,
                //     options: {
                //         hmr:process.env.NODE_ENV==='development'
                //     }
                // },
                'style-loader',
                "css-loader",
                {
                    loader: 'postcss-loader',
                    options: {
                        plugins: function () { 
                            return [autoprefixer('last 5 version')]
                        }
                    }
                },
                'sass-loader'
            ]
        },
        {
            test: /\.(png|jpg|jpeg|gif|icon|woff|eot|svg|ttf)$/i, // i  忽略大小写
            loader: [
                'url-loader?limit=1024&name=img/[name]-[hash:16].[ext]',
                'image-webpack-loader' //压缩图片
            ]
        }
  	]
  },

  plugins: [
    new uglify(),//压缩优化js文件
    new htmlWebpackPlugin({
      minify: { //minify是对html进行压缩
      	removeComments: true, //是否移除注释 默认是false
      	collapseWhitespace: true //是否去除空格 默认false
      },
      filename: 'index.html',
      template: path.resolve(__dirname, 'src/index.html'),//html模板所在文件路径
      title: '新闻头条',
      chunksSortMode: 'manual', //排序,按照chunks的数组顺序排序
      chunks: ['index'],
      excludeChunks: ['node_modules'],
      hash: true
    }),
    new htmlWebpackPlugin({
      minify: {
        removeComments: true,
        collapseWhitespace: true
      },
      filename: 'detail.html',
      template: path.resolve(__dirname, 'src/detail.html'),
      title: '新闻详情',
      chunksSortMode: 'manual',
      chunks: ['detail'],
      excludeChunks: ['node_modules'],
      hash: true
    }),
    new htmlWebpackPlugin({
      minify: {
        removeComments: true,
        collapseWhitespace: true
      },
      filename: 'collections.html',
      template: path.resolve(__dirname, 'src/collections.html'),
      title: '我的收藏',
      chunksSortMode: 'manual',
      chunks: ['collections'],
      excludeChunks: ['node_modules'],
      hash: true
    }),
    //如果把css提取成单独的css文件,这里设置的是提取后保存的文件名
    // new MiniCssExtractPlugin({ 
    //     filename:'css/[name].css'
    // })
  ],

  devServer: {
  	watchOptions: {
  		ignored: /node_modules/
    },
    open:true,
  	host: 'localhost',
  	port: 3000
  }
};

module.exports = config;