webpack4搭建脚手架-踩坑记_04

webpack4入门和使用

webpack介绍

这是webpak的上的基本的介绍:本质上,webpack 是一个现代 JavaScript 应用程序的静态模块打包器(static module bundler)。在 webpack 处理应用程序时,它会在内部创建一个依赖图(dependency graph),用于映射到项目需要的每个模块,然后将所有这些依赖生成到一个或多个bundle。
webpack的文档 https://webpack.docschina.org...
新接手的项目,从轮子开始就自己搭建。网上也找了很久的,也没找到很合适的轮子,那就自己建一个吧。wewebpack4 也更新了很多东西。

新建项目

mkdir webpack-init
cd webpack-init
npm init

之后就跟着提示把package.json中的信息补充完整就可以了.

新建JS文件

目录

.
├── ./package.json
├── ./src
│   └── ./src/index.js
├── ./webpack.config.js
├── ./yarn-error.log
└── ./yarn.lock

其中webpack.config.js 如下

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin'); //通过 npm 安装

module.exports = {
    entry: './src/index.js', //入口文件,src下的index.js
    output: {
        path: path.join(__dirname, 'dist'), // 出口目录,dist文件
        filename: '[name].[hash].js' //这里name就是打包出来的文件名,因为是单入口,就是main,多入口下回分解
    },
    module: {},
    plugin: [],
    devServer: {
        contentBase: path.join(__dirname, 'dist'), //静态文件根目录
        port: 8080, // 端口
        host: 'localhost',
        overlay: true,
        compress: true // 服务器返回浏览器的时候是否启动gzip压缩
    }
};

添加插件

js文件加载

yarn add ]babel-core babel-loader babel-preset-es2015 babel-preset-react babel-preset-stage-0 -D

新建.babelrc 文件

 {
   "presets": [
     "es2015",
     "react",
     "stage-0"
   ],
   "plugins": []
//babel-core 调用Babel的API进行转码
//babel-loader
//babel-preset-es2015 用于解析 ES6
//babel-preset-react 用于解析 JSX
//babel-preset-stage-0 用于解析 ES7 提案

 }
 /*src文件夹下面的以.js结尾的文件,要使用babel解析*/
 /*cacheDirectory是用来缓存编译结果,下次编译加速*/
 module: {
     rules: [{
         test: /\.js$/,
         use: ['babel-loader?cacheDirectory=true'],
         include: path.join(__dirname, 'src')
     }]
 }

css文件加载

yarn add style-loader -D
yarn add  css-loader -D

添加配置:

 rules: {
        test: /\.css$/,
        use: ['style-laoder', 'css-loader'],
        include: path.join(__dirname, 'src'), //限制范围,提高打包速度
        exclude: /node_modules/
    }

html模板生成

//通过 npm 安装 webpack.config.js头部添加
const HtmlWebpackPlugin = require('html-webpack-plugin'); 
//插件添加
plugin: [
        // 通过new一下这个类来使用插件
        new HtmlWebpackPlugin({
            // 用哪个html作为模板
            // 在src目录下创建一个index.html页面当做模板来用
            template: './src/index.html',
            hash: true // 会在打包好的bundle.js后面加上hash串
        })
    ]

复制静态资源

yarn add copy-webpack-plugin -D

添加插件配置


new CopyWebpackPlugin([
  {
    from: path.resolve(__dirname, 'public/static'),
    to: path.resolve(__dirname, 'dist/static'),
    ignore: ['.*']
  }
])

webpack.base.conf.js

// webpack.base.conf.js
const path = require('path');

const APP_PATH = path.resolve(__dirname, '../src');
const DIST_PATH = path.resolve(__dirname, '../dist');
module.exports = {
  entry: {
    app: ['./src/index.js'],
  },
  output: {
    // filename: 'js/[name].[hash].js', //使用hash进行标记,
    filename: '[name].[chunkhash].js',
    chunkFilename: '[name].[chunkhash].js',
    path: DIST_PATH,
  },
  module: {
    rules: [
      {
        test: /\.js|jsx$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
        },
      },
      {
        test: /\.scss$/,
        use: [
          {
            loader: 'style-loader', // 将 JS 字符串生成为 style 节点
          },
          {
            loader: 'css-loader', // 将 CSS 转化成 CommonJS 模块
          },
          {
            loader: 'sass-loader', // 将 Sass 编译成 CSS
          },
        ],
      },
      {
        // 使用css配置
        test: /\.css$/,
        loader: 'style-loader!css-loader',
      },
      {
        // 使用less配置
        test: /\.less$/,
        loader: 'style-loader!css-loader',
      },
      {
        test: /\.(png|jpg|gif)$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: 8192,
              name: 'images/[hash].[ext]', // 所有图片在一个目录
            },
          },
        ],
      },
    ],
  },
};

webpack.dev.conf.js

const path = require('path');
const merge = require('webpack-merge');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
const baseWebpackConfig = require('./webpack.base.conf.js');

module.exports = merge(baseWebpackConfig, {
  mode: 'development',
  output: {
    filename: 'js/[name].[hash].js',
  },
  // 源错误检查
  devtool: 'inline-source-map',
  plugins: [
    // 处理html
    new HtmlWebpackPlugin({
      template: 'public/index.html',
      inject: 'body',
      minify: {
        html5: true,
      },
      hash: false,
    }),
    // 热更新
    new webpack.HotModuleReplacementPlugin(),
  ],
  // 热更新
  devServer: {
    port: '3200',
    contentBase: path.join(__dirname, '../public'),
    historyApiFallback: true,
    hot: true, // 开启
    https: false,
    noInfo: true,
    open: true,
    proxy: {
      // '/': {
      //   target: 'http://internal.api.pre.ucloudadmin.com',
      //   changeOrigin: true,
      //   secure: false,
      // },
    },
  },
});

webpack.prod.conf.js 文件

// webpack.prod.conf.js 文件
const CleanWebpackPlugin = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer')
  .BundleAnalyzerPlugin;
const CopyWebpackPlugin = require('copy-webpack-plugin');
const merge = require('webpack-merge'); // 合并配置
const webpack = require('webpack');
const baseWebpackConfig = require('./webpack.base.conf');

module.exports = merge(baseWebpackConfig, {
  mode: 'production', // mode是webpack4新增的模式
  plugins: [
    new HtmlWebpackPlugin({
      template: 'public/index.html',
      title: 'Pareto', // 更改HTML的title的内容
      favicon: 'public/favicon.ico',
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeAttributeQuotes: true,
      },
    }),
    new CleanWebpackPlugin(['../dist'], { allowExternal: true }),
    new BundleAnalyzerPlugin(),
    new CopyWebpackPlugin([
      {
        from: 'public/index.css',
        to: '../dist',
      },
    ]),
  ],
  optimization: {
    // runtimeChunk: {
    //     name: "manifest"
    // },
    splitChunks: {
      cacheGroups: {
        commons: {
          chunks: 'initial',
          minChunks: 2,
          maxInitialRequests: 5,
          minSize: 0,
        },
        vendor: {
          // 将第三方模块提取出来
          test: /node_modules/,
          chunks: 'initial',
          name: 'vendor',
          priority: 10, // 优先
          enforce: true,
        },
      },
    },
  },
});
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值