In order to streamline the directory size of the packaging output dist
, we can introduce CDN external packages to reduce the packaging volume and speed up the packaging. Here is an introduction Vite
to Webpack
how to introduce it React CDN外部包
.
1. Vite introduces CDN package
1. Install the plug-in
npm i @vitejs/plugin-react-refresh vite-plugin-cdn-import -D
package.json
If it has been installed before react
, remember to clear it.
2. Manual configuration
// vite.config.js
import reactRefresh from '@vitejs/plugin-react-refresh'
import importToCDN from 'vite-plugin-cdn-import'
export default {
plugins: [
importToCDN({
modules: [
{
name: 'react',
var: 'React',
path: `umd/react.production.min.js`,
},
{
name: 'react-dom',
var: 'ReactDOM',
path: `umd/react-dom.production.min.js`,
},
],
}),
],
}
import
name: module name, which is the package name when introduced in the project , for example:import React, { useState } from 'react';
var
var: global variable name defined by cdn external package .- path: the address of the cdn external package.
3. Automatic configuration
// vite.config.js
import reactRefresh from '@vitejs/plugin-react-refresh'
import importToCDN, {
autoComplete } from 'vite-plugin-cdn-import'
export default {
plugins: [
importToCDN({
modules: [
autoComplete('react'),
autoComplete('react-dom')
],
}),
reactRefresh(),
],
}
Packages supported by automatic configuration:
"react" | "react-dom" | "react-router-dom" |
"antd" | "ahooks" | "@ant-design/charts" |
"vue" | "vue2" | "@vueuse/shared" |
"@vueuse/core" | "moment" |
"eventemitter3" | "file-saver" |
"browser-md5-file" | "xlsx | "crypto-js" |
"axios" | "lodash" | "localforage"
2. Webpack introduces CDN package
package.json
If it has been installed before react
, remember to clear it.
1. Configure config/config.js
export default defineConfig({
// webpack5: {
// externals: {
// react: "React"
// }
// },
chainWebpack(config) {
config.externals({
// '模块名': '全局变量名'
react: 'React',
});
}
})
2. Modify the html template
Open it src\pages\document.ejs
and introduce the following files in the tag:
<script src="https://cdn.bootcdn.net/ajax/libs/react/18.2.0/umd/react.development.js"></script>
3. CDN open source package warehouse
Recommended CDN package warehouse: https://www.bootcdn.cn/react/Recommended
version UMD
, for example:
- UMM: A common module version of UMD version, supporting multiple module methods
- EJS: CommonJS - mostly used in Nodejs projects.
- ESM: ECMAScript Modules, based on the static introduction mechanism of esmodule in es6.