20180710-Webpack

2018-07-16  本文已影响0人  HeyDelilah

Webpack

20180710

本质上,webpack 是一个现代 JavaScript 应用程序的静态模块打包器(module bundler)。当 webpack 处理应用程序时,它会递归地构建一个依赖关系图(dependency graph),其中包含应用程序需要的每个模块,然后将所有这些模块打包成一个或多个 bundle。

简化版打包过程:

  1. 从入口文件开始,分析所有依赖(如搜索关键字 “import”);递归
  2. 翻译: 如ES6转成正常js等;根据配置的loader来处理
  3. 分析是否属于同一个chunk (简单区分:主代码&异步代码)
  4. 合并 module (如 index.js 和 HelloWorld.js 就可合并成同一个)
  1. 分配 ID
  2. 合并文件
image

配置一个 React 项目

初始化

npm init; git init
.gitignore

babel

npm install --save-dev babel-core babel-cli babel-preset-env babel-preset-react

.babelrc

{
  "presets": ["env", "react"]
}

Webpack

npm install --save-dev webpack webpack-cli webpack-dev-server style-loader css-loader babel-loader

webpack.config.js

const path = require("path");
const webpack = require("webpack");

module.exports = {
  entry: "./src/index.js",
  mode: "development",
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /(node_modules|bower_components)/,
        loader: 'babel-loader',
        options: { presets: ['env'] }
      },
      {
        test: /\.css$/,
        use: [ 'style-loader', 'css-loader' ]
      }
    ]
  },
  resolve: { extensions: ['*', '.js', '.jsx'] },
  output: {
    path: path.resolve(__dirname, "dist/"),
    publicPath: "/dist/",
    filename: "bundle.js"
  },
  devServer: {
    contentBase: path.join(__dirname, "public/"),
    port: 3000,
    publicPath: "http://localhost:3000/dist/",
    hotOnly: true
  },
  plugins: [ new webpack.HotModuleReplacementPlugin() ]
};

React

react@16.4.1 and react-dom@16.4.1.

文件目录结构

+-- public
| +-- index.html
+-- src
| +-- App.css
| +-- App.js
| +-- index.js
+-- .babelrc
+-- .gitignore
+-- package-lock.json
+-- package.json
+-- webpack.config.js

启动

webpack-dev-server --mode development

react-hot-loader

import React, { Component} from "react";
import {hot} from "react-hot-loader";

...

export default hot(module)(App);

资料

  1. webpack原理学习: https://www.jianshu.com/p/b36239be4d95
  2. Creating a React App… From Scratch. https://blog.usejournal.com/creating-a-react-app-from-scratch-f3c693b84658
上一篇下一篇

猜你喜欢

热点阅读