Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【Webpack】 #1

Open
zh-rocco opened this issue Jun 7, 2018 · 0 comments
Open

【Webpack】 #1

zh-rocco opened this issue Jun 7, 2018 · 0 comments
Assignees
Labels

Comments

@zh-rocco
Copy link
Owner

zh-rocco commented Jun 7, 2018

webpack.config.js Hot Reload

package.json

{
  "scripts": {
    "dev": "nodemon --watch webpack.config.js --exec webpack-dev-server --hot"
  }
}

参考:

Proxy Hot Reload

思路

  1. fs.watch(): 监听 file
  2. require.resolve('filePath'): 获取 module 的 key
  3. delete require.cache['cacheKey']: 删除 cache

webpack-proxy.config.js

module.exports = {
  target: 'http://localhost:3000/',
};

webpack.config.js

const fs = require('fs');
const proxyConfig = require('./webpack-proxy.config');

let proxyOptions = {
  context: '/api',
  target: proxyConfig.target,
  pathRewrite: proxyConfig.pathRewrite,
  changeOrigin: true,
};

fs.watch('./proxy-config.js', () => {
  delete require.cache[require.resolve('./webpack-proxy.config')];
  try {
    const newProxyConfig = require('./webpack-proxy.config');
    if (proxyOptions.target !== newProxyConfig.target) {
      console.log('Proxy target changed:', newProxyConfig.target);
      proxyOptions = {
        context: '/api',
        target: newProxyConfig.target,
        pathRewrite: newProxyConfig.pathRewrite,
        changeOrigin: true,
      };
    }
  } catch (e) {
    // eslint-disable-line
  }
});

module.exports = {
  // ...
  devServer: {
    proxy: [
      function proxy() {
        return proxyOptions;
      },
    ],
  }
}

参考:

在同一个页面中加载多个 webpack 实例

方式一

webpack.config.js

module.exports = {
  output: {
    jsonpFunction: 'webpackJsonp' + Date.now(),
  },
};

方式二

安装依赖

npm i modify-chunk-id-webpack-plugin -D

webpack.config.js

const ModifyChunkIdPlugin = require('modify-chunk-id-webpack-plugin');

module.exports = {
  plugins: [
    // ...
    new ModifyChunkIdPlugin({ random: process.env.NODE_ENV === 'development' }),
  ],
};

参考:

CSS 打包顺序

注意 CSS 的引用顺序, 一定要将外部依赖的 CSS 库先于项目 CSS 引用

以 Vue 为例

main.js

import Vue from 'vue';
// 第三方 CSS 库
import 'path/to/thirdparty.css';

import App from './App';

App.vue

<style lang="less">
  // 项目CSS
  @import 'path/to/index.less';

  .ellipsis {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
</style>

模块上下文 require.context

3 个参数:要搜索的文件夹目录,是否还应该搜索它的子目录,以及一个匹配文件的正则表达式

require.context(directory, useSubdirectories = false, regExp = /^\.\//);

示例:

require.context('./test', false, /\.test\.js$/);
//(创建了)一个包含了 test 文件夹(不包含子目录)下面的、所有文件名以 `.test.js` 结尾的、能被 require 请求到的文件的上下文。

加载所有的图片

const imageContext = require.context('@/assets/kittens/', false, /\.jpg$/);

const img = imageContext('./name.jpg');

提取公共依赖

webpack 配置:

module.exports = {
  // ...
  externals: {
    vue: 'Vue',
    'element-ui': 'ELEMENT',
  },
};

HTML 单独引入:

<head>
  <script src="path/to/vue.js"></script>
  <script src="path/to/element-ui.js"></script>
</head>

模块分包 /* webpackChunkName: name */

export default [
  {
    path: '/',
    component: () => import(/* webpackChunkName: "index" */ '@/views/Index.vue'),
    children: [
      {
        path: 'page-a',
        component: () => import(/* webpackChunkName: "page" */ '@/views/PageA.vue'),
      },
      {
        path: 'page-b',
        component: () => import(/* webpackChunkName: "page" */ '@/views/PageB.vue'),
      },
    ],
  },
];

打包后输出 indexpage 两个 chunk

lodash 按需加载

1. 安装依赖

yarn add babel-plugin-lodash -D

2. 配置 babel

babel.config.js

module.exports = {
  plugins: ['lodash'],
};

3. 使用

Transforms

import _ from 'lodash';
import { add } from 'lodash/fp';

const addOne = add(1);
_.map([1, 2, 3], addOne);

roughly to

import _add from 'lodash/fp/add';
import _map from 'lodash/map';

const addOne = _add(1);
_map([1, 2, 3], addOne);

参考: babel-plugin-lodash

使用 optional chaining 语法( obj?.prop

1. 安装依赖

yarn add @babel/plugin-proposal-optional-chaining -D

2. 配置 babel

babel.config.js

module.exports = {
  plugins: ["@babel/plugin-proposal-optional-chaining"]
};

3. 使用

Transforms

a?.b

roughly to

a == null ? undefined : a.b

参考: Optional Chaining for JavaScript

图解 webpack

webpack 编译流程

webpack 编译流程

webpack 进阶

@zh-rocco zh-rocco self-assigned this Jul 5, 2018
Repository owner locked as off-topic and limited conversation to collaborators Jul 5, 2018
Repository owner unlocked this conversation Aug 17, 2018
Repository owner locked as resolved and limited conversation to collaborators Aug 17, 2018
@zh-rocco zh-rocco changed the title Webpack 【Webpack】 Sep 3, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Projects
None yet
Development

No branches or pull requests

1 participant