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: code splitting base on directives #305

Merged
merged 4 commits into from
Dec 17, 2023
Merged
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@
"rollup": "^4.6.1",
"rollup-plugin-dts": "^6.1.0",
"rollup-plugin-swc3": "^0.11.0",
"rollup-preserve-directives": "^1.0.1",
"rollup-preserve-directives": "^1.1.0",
"tslib": "^2.6.2"
},
"peerDependencies": {
Expand Down
18 changes: 9 additions & 9 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

34 changes: 30 additions & 4 deletions src/build-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@ import type {
ExportPaths,
FullExportCondition,
} from './types'
import type { InputOptions, OutputOptions, Plugin } from 'rollup'
import type { GetManualChunk, InputOptions, OutputOptions, Plugin } from 'rollup'
import { type TypescriptOptions } from './typescript'

import { resolve, dirname, extname, join } from 'path'
import path, { resolve, dirname, extname, join, basename } from 'path'
import { wasm } from '@rollup/plugin-wasm'
import { swc } from 'rollup-plugin-swc3'
import commonjs from '@rollup/plugin-commonjs'
Expand All @@ -22,6 +22,7 @@ import { sizeCollector } from './plugins/size-plugin'
import { inlineCss } from './plugins/inline-css'
import { rawContent } from './plugins/raw-plugin'
import preserveDirectives from 'rollup-preserve-directives'
import { prependDirectives } from './plugins/prepend-directives'
import {
getTypings,
getExportPaths,
Expand Down Expand Up @@ -179,6 +180,7 @@ async function buildInputConfig(
inlineCss({ exclude: /node_modules/ }),
rawContent({ exclude: /node_modules/ }),
preserveDirectives(),
prependDirectives(),
replace({
values: getBuildEnv(options.env || []),
preventAssignment: true,
Expand Down Expand Up @@ -257,6 +259,25 @@ function hasEsmExport(
return Boolean(hasEsm || tsCompilerOptions?.esModuleInterop)
}

const splitChunks: GetManualChunk = (id, ctx) => {
const moduleInfo = ctx.getModuleInfo(id)
const moduleMeta = moduleInfo?.meta
if (!moduleInfo || !moduleMeta) {
return
}

const directives = (moduleMeta.preserveDirectives || { directives: [] }).directives
.map((d: string) => d.replace(/^use /, ''))
.filter((d: string) => d !== 'strict')

const moduleLayer = directives[0]
if (moduleLayer && !moduleMeta.isEntry) {
const chunkName = path.basename(id, path.extname(id))
return `${chunkName}-${moduleLayer}`
}
return
}

function buildOutputConfigs(
pkg: PackageMetadata,
exportPaths: ExportPaths,
Expand Down Expand Up @@ -289,17 +310,22 @@ function buildOutputConfigs(
)

// If there's dts file, use `output.file`
const dtsPathConfig = dtsFile ? { file: dtsFile } : { dir: dtsDir }
const dtsPathConfig = dtsFile ? { dir: dirname(dtsFile) } : { dir: dtsDir }
const outputFile: string = (dtsFile || file)!

return {
name: pkg.name || name,
...(dts ? dtsPathConfig : { file: file }),
...(dts ? dtsPathConfig : { dir: dirname(outputFile!) }),
format,
exports: 'named',
esModule: useEsModuleMark || 'if-default-prop',
interop: 'auto',
freeze: false,
strict: false,
sourcemap: options.sourcemap,
manualChunks: splitChunks,
chunkFileNames: '[name].js',
entryFileNames: basename(outputFile!),
}
}

Expand Down
27 changes: 27 additions & 0 deletions src/plugins/prepend-directives.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import type { Plugin } from 'rollup'

export function prependDirectives(): Plugin {
return {
name: 'prependDirective',
transform: {
order: 'post',
handler(code, id) {
const moduleInfo = this.getModuleInfo(id)
if (moduleInfo?.meta?.preserveDirectives) {
const firstDirective = moduleInfo.meta.preserveDirectives.directives[0]
console.log('prepend', id, firstDirective)
if (firstDirective) {
const directive = firstDirective.value
const directiveCode = `'${directive}';`
return directiveCode + '\n' + code
}
}
return {
code,
map: null,
}
}
}
}
}

20 changes: 20 additions & 0 deletions test/integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -398,6 +398,26 @@ const testCases: {
`"thisismydata"`,
)
},
},
{
name: 'server-components',
args: [],
async expected(dir) {
const distFiles = [
join(dir, 'dist/index.js'),
join(dir, 'dist/actions-server.js'),
join(dir, 'dist/ui-client.js'),
join(dir, 'dist/ui.js'),
]
for (const f of distFiles) {
expect(await existsFile(f)).toBe(true)
}
// split chunks
expect(await fs.readFile(distFiles[1], 'utf-8')).toContain('use server')
expect(await fs.readFile(distFiles[2], 'utf-8')).toContain('use client')
// client component as an entry will remain the directive
expect(await fs.readFile(distFiles[3], 'utf-8')).toContain('use client')
},
}
]

Expand Down
10 changes: 10 additions & 0 deletions test/integration/server-components/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"type": "module",
"exports": {
".": "./dist/index.js",
"./ui": "./dist/ui.js"
},
"peerDependencies": {
"react": "*"
}
}
5 changes: 5 additions & 0 deletions test/integration/server-components/src/actions.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
'use server'

export async function action() {
return 'server-action'
}
2 changes: 2 additions & 0 deletions test/integration/server-components/src/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export { Button } from './ui'
export { action } from './actions'
8 changes: 8 additions & 0 deletions test/integration/server-components/src/ui.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
'use client'

import React, { useState } from 'react'

export function Button() {
const [count] = useState(0)
return React.createElement('button', `count: ${count}`)
}
5 changes: 1 addition & 4 deletions test/unit/use-client/__snapshot__/use-client.js.snapshot
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
'use client';
'use strict';
function client() {
return React.useState(null);
}
import { c as client } from './client-client.js';

var input = (()=>{
return client();
Expand Down
Original file line number Diff line number Diff line change
@@ -1 +1 @@
"use strict";var t=()=>React.useState(null);export{t as default};
"use strict";import{c as t}from"./client-client.js";var e=()=>t();export{e as default};