• 周四. 4月 25th, 2024

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

umijs 开发优化和生产优化

admin

11月 28, 2021

.umirc.ts

import { defineConfig } from 'umi';

import dev from './config/dev';
import prod from './config/prod';

console.log(process.env.NODE_ENV);
const envConfig = 'development' === process.env.NODE_ENV ? dev : prod;

export default defineConfig({
  webpack5: {}, // 使用webpack 5
  nodeModulesTransform: {
    type: 'none',
  },
  routes: [{ path: '/', component: '@/pages/index' }],
  fastRefresh: {},
  ...envConfig,
});

config/dev

开发时使用 chunk,cache和esbuild-loader 减少打包时间

esbuild-loader 不支持 typescript 的 emitDecoratorMetadata, 如果你需要 emitDecoratorMetadata 可以将 esbuild-loader 换成 swc

import { defineConfig } from 'umi';

export default defineConfig({
  hash: false,
  devServer: {
    // writeToDisk: true,
  },
  chunks: ['vendors', 'umi'],
  chainWebpack: function (config, { webpack }) {
    config.merge({
      // https://webpack.js.org/configuration/cache/
      cache: {
        type: 'filesystem',
      },
      optimization: {
        moduleIds: 'deterministic',
        splitChunks: {
          cacheGroups: {
            vendor: {
              test: /[\/]node_modules[\/]/,
              name: 'vendors',
              chunks: 'all',
            },
          },
        },
      },
      module: {
        rules: [
          {
            test: /.tsx?$/,
            loader: 'esbuild-loader',
            options: {
              loader: 'tsx',
              target: 'esnext',
            },
          },
        ],
      },
    });
  },
});

config/prod

打包生产时 能用cdn的就用cdn

import { defineConfig } from 'umi';
import * as pkg from '../package.json';

const externalsConfig: any = {
  lodash: {
    name: '_',
    cdn: (version: string) =>
      `https://cdnjs.cloudflare.com/ajax/libs/react/${version}/umd/react.production.min.js`,
  },
  react: {
    name: 'React',
    cdn: (version: string) =>
      `https://cdnjs.cloudflare.com/ajax/libs/react-dom/${version}/umd/react-dom.production.min.js`,
  },
  'react-dom': {
    name: 'ReactDOM',
    cdn: (version: string) =>
      `https://cdnjs.cloudflare.com/ajax/libs/lodash.js/${version}/lodash.min.js`,
  },
};

const externals: any = {};
const scripts: string[] = [];
for (const pname in externalsConfig) {
  externals[pname] = externalsConfig[pname].name;
  if (pname in pkg.dependencies) {
    const version = (pkg.dependencies as any)[pname].replace(/^D/, '');
    scripts.push(externalsConfig[pname].cdn(version));
  }
}

export default defineConfig({
  hash: true,
  chainWebpack: function (config, { webpack }) {
    config.merge({
      optimization: {
        minimize: true,
        usedExports: true,
      },
    });
  },
  externals,
  scripts,
});

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注