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

Show inlined error if the "use client" directive is not before other statements/expressions #42507

Merged
merged 2 commits into from Nov 7, 2022
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
40 changes: 33 additions & 7 deletions packages/next/server/next-typescript.ts
Expand Up @@ -187,19 +187,33 @@ export function createTSPlugin(modules: {
)
}

function getIsClientEntry(fileName: string) {
function getIsClientEntry(
fileName: string,
throwOnInvalidDirective?: boolean
) {
const source = info.languageService.getProgram()?.getSourceFile(fileName)
if (source) {
let isClientEntry = false
let isDirective = true

ts.forEachChild(source!, (node) => {
if (isClientEntry || !isDirective) return

if (isDirective && ts.isExpressionStatement(node)) {
if (ts.isStringLiteral(node.expression)) {
if (node.expression.text === 'use client') {
if (
ts.isExpressionStatement(node) &&
ts.isStringLiteral(node.expression)
) {
if (node.expression.text === 'use client') {
if (isDirective) {
isClientEntry = true
} else {
if (throwOnInvalidDirective) {
throw {
messageText:
'The `"use client"` directive must be put at the top of the file.',
start: node.expression.getStart(),
length:
node.expression.getEnd() - node.expression.getStart(),
}
}
}
}
} else {
Expand Down Expand Up @@ -473,7 +487,19 @@ export function createTSPlugin(modules: {

const source = info.languageService.getProgram()?.getSourceFile(fileName)
if (source) {
const isClientEntry = getIsClientEntry(fileName)
let isClientEntry = false

try {
isClientEntry = getIsClientEntry(fileName, true)
} catch (e: any) {
prior.push({
file: source,
category: ts.DiagnosticCategory.Error,
code: 71004,
Copy link
Member

@huozhi huozhi Nov 7, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what does code 71004 here do? could we add some comments for it? not blocking just for reminder

...e,
})
isClientEntry = false
}

ts.forEachChild(source!, (node) => {
if (ts.isImportDeclaration(node)) {
Expand Down