前后端分离项目的 CDN 加速优化策略
一、CDN 基础配置
1. 选择合适的 CDN 服务
根据项目需求和预算选择合适的 CDN 服务提供商:
- 国际: Cloudflare, Akamai, AWS CloudFront, Fastly
- 国内: 阿里云 CDN, 腾讯云 CDN, 七牛云, 又拍云, 百度云加速
2. 配置 CDN 域名
- 在 CDN 服务商平台创建加速域名(如
static.yourdomain.com) - 配置源站信息(指向你的源服务器或对象存储)
- 配置 CNAME 记录,将加速域名指向 CDN 服务商提供的域名
- 配置 HTTPS 证书(强烈推荐)
二、前端构建配置
1. Webpack 配置
// webpack.config.js
const isProd = process.env.NODE_ENV === 'production';
const CDN_URL = isProd ? 'https://static.yourdomain.com/' : '/';
module.exports = {
output: {
filename: 'js/[name].[contenthash:8].js',
path: path.resolve(__dirname, 'dist'),
publicPath: CDN_URL, // 关键配置:资源的基础路径
},
// 图片、字体等资源配置
module: {
rules: [
{
test: /\.(png|jpe?g|gif|svg)$/i,
type: 'asset',
generator: {
filename: 'images/[name].[hash:8][ext]',
},
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/i,
type: 'asset/resource',
generator: {
filename: 'fonts/[name].[hash:8][ext]',
},
},
],
},
};
2. Vite 配置
// vite.config.js
export default defineConfig(({ command, mode }) => {
const isProd = mode === 'production';
const CDN_URL = isProd ? 'https://static.yourdomain.com/' : '/';
return {
base: CDN_URL, // 公共基础路径
build: {
rollupOptions: {
output: {
// 自定义构建输出
chunkFileNames: 'js/[name]-[hash].js',
entryFileNames: 'js/[name]-[hash].js',
assetFileNames: ({name}) => {
if (/\.(gif|jpe?g|png|svg)$/.test(name)) {
return 'images/[name]-[hash][extname]';
}
if (/\.(woff2?|ttf|eot)$/.test(name)) {
return 'fonts/[name]-[hash][extname]';
}
return 'assets/[name]-[hash][extname]';
},
},
},
},
};
});