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

feat: support rename main css chunk name #5159

Merged
merged 8 commits into from
Feb 17, 2022
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions examples/basic-mpa-vite/src/pages/About/index.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
.test {
color: #000000;
font-weight: bold;
}
1 change: 1 addition & 0 deletions packages/plugin-react-app/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

## 2.2.1

- [fix] support userConfig `cssChunkNames`
- [fix] bump version of `@builder/pack`(^0.6.0)
- [fix] remove `webpackHotDevClient`
- [fix] `vitePlugins` only take effect when `vite` is true
Expand Down
5 changes: 5 additions & 0 deletions packages/plugin-react-app/src/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@ module.exports = function() {
defaultValue: false,
validation: 'boolean|object'
},
{
name: 'cssChunkNames',
defaultValue: '',
validation: 'string|object',
},
{
name: 'vitePlugins',
defaultValue: [],
Expand Down
4 changes: 4 additions & 0 deletions packages/vite-service/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# CHANGELOG

## 2.1.1

- [feat] plugin for rename main css chunk name

## 2.1.0

- [feat] refactor html plugin for SSR render when development
Expand Down
2 changes: 1 addition & 1 deletion packages/vite-service/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@builder/vite-service",
"version": "2.1.0",
"version": "2.1.1",
"description": "vite implementation",
"author": "ice-admin@alibaba-inc.com",
"homepage": "",
Expand Down
85 changes: 85 additions & 0 deletions packages/vite-service/src/plugins/cssChunk.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import * as path from 'path';
import * as fse from 'fs-extra';
import { formatPath } from '@builder/app-helpers';
import type { Plugin } from 'vite';

export interface EmittedAsset {
fileName?: string;
name?: string;
source?: string | Uint8Array;
type: 'asset';
}

function parseCssName(name: string, index: number) {
let cssName = name.replace(path.extname(name), '');
if (index > 0) {
cssName = `${cssName}-${index}`;
}
return `${cssName}.css`;
}

const addTrailingSlash = (str: string): string => {
return str[str.length - 1] === '/' ? str : `${str}/`;
};

type ChunkName = string | Record<string, string>;

export const cssChunk = (chunkName: ChunkName): Plugin => {
let viteManifestPlugin: Plugin;
let fileData: any;
let outputDir = '';
let base = '';
return {
name: 'vite-plugin-css-chunk-name',
config(cfg, { command }) {
if (command === 'build') {
cfg.build.manifest = true;
outputDir = path.join(cfg.root, cfg.build.outDir);
base = addTrailingSlash(cfg.base);
}
},
buildStart({ plugins }) {
viteManifestPlugin = plugins && plugins.find(({ name }) => name === 'vite:manifest');
},
generateBundle: async (options, bundle, isWrite) => {
await viteManifestPlugin.generateBundle.call({
...(this as any),
emitFile: (file: EmittedAsset) => {
fileData = JSON.parse(file.source as string);
return '__manifest';
}}, options, bundle, isWrite);
},
closeBundle: () => {
Object.keys(fileData).forEach(key => {
if (fileData[key].isEntry) {
const entryName = key.replace(path.extname(key), 'key');
const cssChunkName = typeof chunkName === 'string' ? chunkName : chunkName[entryName];
const entryData = fileData[key];
const entryCss = entryData?.css;
if (entryCss && cssChunkName) {
const htmlPath = path.join(outputDir, entryData.src);
let htmlContent = entryData?.src && fse.readFileSync(htmlPath, 'utf8');
let cssIndex = 0;
entryCss.forEach((cssLink: string) => {
const cssDir = path.dirname(cssLink);
const sourceCss = path.join(outputDir, cssLink);
const cssName = parseCssName(cssChunkName, cssIndex);
const renamedCss = formatPath(path.join(cssDir, cssName));
if (cssLink !== renamedCss) {
fse.moveSync(sourceCss, path.join(outputDir, cssDir, cssName));
// replace css link
htmlContent = htmlContent.replace(/<link[\s\S]*href=["']([^'"]*)["'][^>]*>/g, (str, matched) => {
return matched === `${base}${cssLink}` ? str.replace(matched, `${base}${renamedCss}`) : str;
});
} else {
console.log('[WARN]', `${chunkName} is conflict with css assets`);
}
cssIndex++;
});
fse.writeFileSync(htmlPath, htmlContent);
}
}
});
}
};
};
1 change: 1 addition & 0 deletions packages/vite-service/src/plugins/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ export * from './polyfill';
export * from './html';
export * from './ignoreHtml';
export * from './mock';
export * from './cssChunk';
2 changes: 2 additions & 0 deletions packages/vite-service/src/wp2vite/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
ignoreHtmlPlugin,
mockPlugin,
ImportDeclarations,
cssChunk,
} from '../plugins';

type Option = BuildOptions & InlineConfig;
Expand Down Expand Up @@ -170,6 +171,7 @@ export const wp2vite = (context: Context): InlineConfig => {
}),
userConfig.ignoreHtmlTemplate ? ignoreHtmlPlugin(rootDir) : null,
...getPluginReact(context),
userConfig.cssChunkNames && cssChunk(userConfig.cssChunkNames as string),
ClarkXia marked this conversation as resolved.
Show resolved Hide resolved
].filter(Boolean),
};
if (userConfig.eslint !== false) {
Expand Down