美文网首页
20180710-Webpack

20180710-Webpack

作者: HeyDelilah | 来源:发表于2018-07-16 21:12 被阅读0次

    Webpack

    20180710

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

    简化版打包过程:

    1. 从入口文件开始,分析所有依赖(如搜索关键字 “import”);递归
    2. 翻译: 如ES6转成正常js等;根据配置的loader来处理
    3. 分析是否属于同一个chunk (简单区分:主代码&异步代码)
    4. 合并 module (如 index.js 和 HelloWorld.js 就可合并成同一个)
    • 是否属于 ESM
    • 是否属于 normal import(如非开头就import,而是在代码执行中再import的情况)
    • 是否属于同一个 chunks
    • 是否 all importer must be included
    • ? try all dependencies optionally
    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

    相关文章

      网友评论

          本文标题:20180710-Webpack

          本文链接:https://www.haomeiwen.com/subject/jbkipftx.html