webpack4搭建腳手架_04

webpack4入門和使用

webpack介紹

這是webpak的上的基本的介紹:本質上,webpack 是一個現代 JavaScript 應用程序的靜態模塊打包器(static module bundler)。在 webpack 處理應用程序時,它會在內部建立一個依賴圖(dependency graph),用於映射到項目須要的每一個模塊,而後將全部這些依賴生成到一個或多個bundle。
webpack的文檔 https://webpack.docschina.org...
新接手的項目,從輪子開始就本身搭建。網上也找了好久的,也沒找到很合適的輪子,那就本身建一個吧。wewebpack4 也更新了不少東西。css

新建項目

mkdir webpack-init
cd webpack-init
npm init

以後就跟着提示把package.json中的信息補充完整就能夠了.html

新建JS文件

目錄html5

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

其中webpack.config.js 以下node

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 文件react

{
   "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

添加配置:webpack

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

添加插件配置git

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,
        },
      },
    },
  },
});
相關文章
相關標籤/搜索