webpack4搭建脚手架-踩坑记_04

发布时间:2019-08-13 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了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,
        },
      },
    },
  },
});

脚本宝典总结

以上是脚本宝典为你收集整理的webpack4搭建脚手架-踩坑记_04全部内容,希望文章能够帮你解决webpack4搭建脚手架-踩坑记_04所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。