Unverified Commit 71f5f258 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Setup require hook in next-server for styled-jsx resolving (#39305)

* Use require hook and alias to resolve styled-jsx

* re-export styled-jsx types from compiled

* fix lint

* add test for styled-jsx css

* setup require hook in server

* compile import path to styled-jsx/style

* revert require hook

* add test for server styled-jsx resolving

* update test

* pre copy styled-jsx assets

* fix styled-jsx dts

* add npmrc for styled-jsx e2e test

* load require hook directly

* rm legacy test

* fix lint

* fix pnpm install error

* split require hook

* only alias styled-jsx

* make styled-jsx resolving statically analyzable

* update test
Co-authored-by: 's avatarJJ Kasper <jj@jjsweb.site>
parent b0f59016
......@@ -192,7 +192,6 @@
"semver": "7.3.7",
"shell-quote": "1.7.3",
"styled-components": "5.3.3",
"styled-jsx": "link:packages/next/node_modules/styled-jsx",
"styled-jsx-plugin-postcss": "3.0.2",
"tailwindcss": "1.1.3",
"taskr": "1.1.0",
......
import _JSXStyle from "next/dist/shared/lib/styled-jsx";
import _JSXStyle from "styled-jsx/style";
export default function Foo() {
return /*#__PURE__*/ React.createElement("div", {
render: function(v) {
......
......@@ -310,7 +310,7 @@ pub fn styled_jsx_import_decl(style_import_name: &str) -> ModuleItem {
})],
src: Str {
span: DUMMY_SP,
value: "next/dist/shared/lib/styled-jsx".into(),
value: "styled-jsx/style".into(),
raw: None,
},
}))
......
import _JSXStyle from "next/dist/shared/lib/styled-jsx";
import _JSXStyle from "styled-jsx/style";
const Component = ()=><>
<header >
<Comp >
......
import _JSXStyle from "next/dist/shared/lib/styled-jsx";
import _JSXStyle from "styled-jsx/style";
export default (()=><div >
<style jsx>
......
import _JSXStyle from "next/dist/shared/lib/styled-jsx";
import _JSXStyle from "styled-jsx/style";
export default {
styles: <_JSXStyle id={"71f03d42ea0ec6"}>{".container.jsx-71f03d42ea0ec6{background:#000;color:white;font-weight:700;height:100px}"}</_JSXStyle>,
className: "jsx-71f03d42ea0ec6"
......
import _JSXStyle from "next/dist/shared/lib/styled-jsx";
import _JSXStyle from "styled-jsx/style";
export default (()=><div >
<style jsx>
......
import _JSXStyle from "next/dist/shared/lib/styled-jsx";
import _JSXStyle from "styled-jsx/style";
export default (()=><div >
<style jsx>
......
import _JSXStyle from "next/dist/shared/lib/styled-jsx";
import _JSXStyle from "styled-jsx/style";
export default (()=><div >
<style jsx>
......
import _JSXStyle from "next/dist/shared/lib/styled-jsx";
import _JSXStyle from "styled-jsx/style";
export default (()=>{
const Element = 'div';
return <div className={"jsx-abb4c2202db1a207"}>
......
import _JSXStyle from "next/dist/shared/lib/styled-jsx";
import _JSXStyle from "styled-jsx/style";
import styles from './styles';
const styles2 = require('./styles2');
// external only
......
import _JSXStyle from "next/dist/shared/lib/styled-jsx";
import _JSXStyle from "styled-jsx/style";
export default class {
render() {
return <div className={"jsx-b2b86d63f35d25ee"}>
......
import _JSXStyle from "next/dist/shared/lib/styled-jsx";
import _JSXStyle from "styled-jsx/style";
export default class {
render() {
return <div className={"jsx-1952086b0a5ae64c"}>
......
import _JSXStyle from "next/dist/shared/lib/styled-jsx";
import _JSXStyle from "styled-jsx/style";
const Test = ()=><div className={"jsx-a9535d7d5f32c3c4"}>
<span className={"jsx-a9535d7d5f32c3c4"}>test</span>
......
import _JSXStyle from "next/dist/shared/lib/styled-jsx";
import _JSXStyle from "styled-jsx/style";
function NavigationItem({ active , className , }) {
return <span className={"jsx-2342aae4628612c6" + " " + (cn({
active
......
import _JSXStyle from "next/dist/shared/lib/styled-jsx";
import _JSXStyle from "styled-jsx/style";
export default (({ children })=><div className={`jsx-${styles.__hash}`}>
<p className={`jsx-${styles.__hash}`}>{children}</p>
......
import _JSXStyle from "next/dist/shared/lib/styled-jsx";
import _JSXStyle from "styled-jsx/style";
const color = 'red';
const otherColor = 'green';
const A = ()=><div className={"jsx-551210e97e875d0e"}>
......
import _JSXStyle from "next/dist/shared/lib/styled-jsx";
import _JSXStyle from "styled-jsx/style";
export default class {
render() {
const Element = 'div';
......
import _JSXStyle from "next/dist/shared/lib/styled-jsx";
import _JSXStyle from "styled-jsx/style";
import styles from './styles2';
export default (({ level =1 })=>{
const Element = `h${level}`;
......
import _JSXStyle from "next/dist/shared/lib/styled-jsx";
import _JSXStyle from "styled-jsx/style";
export default (({ level =1 })=>{
const Element = `h${level}`;
return <Element className={"jsx-fca64cc3f069b519" + " " + "root"}>
......
import _JSXStyle from "next/dist/shared/lib/styled-jsx";
import _JSXStyle from "styled-jsx/style";
const darken = (c)=>c;
const color = 'red';
const otherColor = 'green';
......
import _JSXStyle from "next/dist/shared/lib/styled-jsx";
import _JSXStyle from "styled-jsx/style";
function test() {
({
styles: <_JSXStyle id={"abb4c2202db1a207"}>{"div.jsx-abb4c2202db1a207{color:red}"}</_JSXStyle>,
......
import _JSXStyle from "next/dist/shared/lib/styled-jsx";
import _JSXStyle from "styled-jsx/style";
import styles, { foo as styles3 } from './styles';
const styles2 = require('./styles2');
export default (()=><div >
......
import _JSXStyle from "next/dist/shared/lib/styled-jsx";
import _JSXStyle from "styled-jsx/style";
import styles from './styles';
export default (()=><div className={`jsx-${styles.__hash}`}>
......
import _JSXStyle from "next/dist/shared/lib/styled-jsx";
import _JSXStyle from "styled-jsx/style";
import styles from './styles';
const styles2 = require('./styles2');
import { foo as styles3 } from './styles';
......
import _JSXStyle from "next/dist/shared/lib/styled-jsx";
import _JSXStyle from "styled-jsx/style";
import React from 'react';
export default (()=><>
......
import _JSXStyle from "next/dist/shared/lib/styled-jsx";
import _JSXStyle from "styled-jsx/style";
const Test = ()=><div className={"jsx-5a206f122d1cb32e"}>
<span className={"jsx-5a206f122d1cb32e"}>test</span>
......
import _JSXStyle from "next/dist/shared/lib/styled-jsx";
import _JSXStyle from "styled-jsx/style";
export default function IndexPage() {
return <div className={"jsx-b6abd0684ba81871"}>
......
import _JSXStyle from "next/dist/shared/lib/styled-jsx";
import _JSXStyle from "styled-jsx/style";
const Test = ()=><div className={"jsx-d47d6adadf14e957"}>
<_JSXStyle id={"d47d6adadf14e957"}>{"body{color:red}:hover{color:red;display:-webkit-box;display:-webkit-flex;display:-moz-box;display:-ms-flexbox;display:flex;-webkit-animation:foo 1s ease-out;-moz-animation:foo 1s ease-out;-o-animation:foo 1s ease-out;animation:foo 1s ease-out}div a{display:none}[data-test]>div{color:red}"}</_JSXStyle>
......
import _JSXStyle from "next/dist/shared/lib/styled-jsx";
import _JSXStyle from "styled-jsx/style";
export default (({ breakPoint })=><div className={_JSXStyle.dynamic([
[
"5d2a0e645566ce9c",
......
import _JSXStyle from "next/dist/shared/lib/styled-jsx";
import _JSXStyle from "styled-jsx/style";
export default function IndexPage() {
return <div className={"jsx-bbdada4ef17d18ef"}>
......
import _JSXStyle from "next/dist/shared/lib/styled-jsx";
import _JSXStyle from "styled-jsx/style";
export default class {
render() {
return <div className={_JSXStyle.dynamic([
......
import _JSXStyle from "next/dist/shared/lib/styled-jsx";
import _JSXStyle from "styled-jsx/style";
const Test = ()=><_JSXStyle id={"94239b6d6b42c9b5"}>{"p{color:red}"}</_JSXStyle>;
export default (()=><div className={"jsx-3822e6e1fb9fa41a"}>
......
import _JSXStyle from "next/dist/shared/lib/styled-jsx";
import _JSXStyle from "styled-jsx/style";
const attrs = {
id: 'test'
};
......
import _JSXStyle from "next/dist/shared/lib/styled-jsx";
import _JSXStyle from "styled-jsx/style";
export default (()=><div className={"jsx-94239b6d6b42c9b5"}>
<p className={"jsx-94239b6d6b42c9b5"}>woot</p>
......
import _JSXStyle from "next/dist/shared/lib/styled-jsx";
import _JSXStyle from "styled-jsx/style";
import Link from "next/link";
export default function IndexPage() {
return <div className={"jsx-9a4b3442d519aae9"}>
......
import _JSXStyle from "next/dist/shared/lib/styled-jsx";
import _JSXStyle from "styled-jsx/style";
export default (()=><div className={"jsx-c7c3a8e231c9215a"}>
<p className={"jsx-c7c3a8e231c9215a"}>test</p>
......
import _JSXStyle from "next/dist/shared/lib/styled-jsx";
import _JSXStyle from "styled-jsx/style";
export default (()=><div className={"jsx-94239b6d6b42c9b5"}>
<p className={"jsx-94239b6d6b42c9b5"}>test</p>
......
import _JSXStyle from "next/dist/shared/lib/styled-jsx";
import _JSXStyle from "styled-jsx/style";
import colors, { size } from './constants';
const color = 'red';
const bar = new String("div.jsx-aaed0341accea8f{font-size:3em}");
......
import _JSXStyle from "next/dist/shared/lib/styled-jsx";
import _JSXStyle from "styled-jsx/style";
export const Red = ({ Component ='button' , })=>{
return <Component className={_JSXStyle.dynamic([
[
......
import _JSXStyle from "next/dist/shared/lib/styled-jsx";
import _JSXStyle from "styled-jsx/style";
export default class {
render() {
return <div className={"jsx-1f6cef12199c3a8f"}>
......
import _JSXStyle from "next/dist/shared/lib/styled-jsx";
import _JSXStyle from "styled-jsx/style";
export default function Home({ fontFamily }) {
return <div className={_JSXStyle.dynamic([
[
......
import _JSXStyle from "next/dist/shared/lib/styled-jsx";
import _JSXStyle from "styled-jsx/style";
export default class {
render() {
return <div className={_JSXStyle.dynamic([
......
import _JSXStyle from "next/dist/shared/lib/styled-jsx";
import _JSXStyle from "styled-jsx/style";
export default class {
render() {
return <div className={_JSXStyle.dynamic([
......
import _JSXStyle from "next/dist/shared/lib/styled-jsx";
import _JSXStyle from "styled-jsx/style";
export default class {
render() {
return <div className={_JSXStyle.dynamic([
......
import _JSXStyle from "next/dist/shared/lib/styled-jsx";
import _JSXStyle from "styled-jsx/style";
export default class {
render() {
return <div className={_JSXStyle.dynamic([
......
import _JSXStyle from "next/dist/shared/lib/styled-jsx";
import _JSXStyle from "styled-jsx/style";
export default class {
render() {
return <div className={_JSXStyle.dynamic([
......
import _JSXStyle from "next/dist/shared/lib/styled-jsx";
import _JSXStyle from "styled-jsx/style";
export default (()=><div className={"jsx-713499aa363d6373"}>
<p className={"jsx-713499aa363d6373"}>test</p>
......
import _JSXStyle from "next/dist/shared/lib/styled-jsx";
import _JSXStyle from "styled-jsx/style";
export default (()=><div className={"jsx-53fd644ab080300c"}>
<p className={"jsx-53fd644ab080300c"}>test</p>
......
import _JSXStyle from "next/dist/shared/lib/styled-jsx";
import _JSXStyle from "styled-jsx/style";
export default (()=><div className={"jsx-1f7963ae04c6466a"}>
<p className={"jsx-1f7963ae04c6466a"}>test</p>
......
import _JSXStyle from "next/dist/shared/lib/styled-jsx";
import _JSXStyle from "styled-jsx/style";
export default (()=><div className={"jsx-1a19bb4817c105dd"}>
<p className={"jsx-1a19bb4817c105dd"}>test</p>
......
import _JSXStyle from "next/dist/shared/lib/styled-jsx";
import _JSXStyle from "styled-jsx/style";
export default (()=><div className={"jsx-938ca197692ef624"}>
<p className={"jsx-938ca197692ef624"}>test</p>
......
import _JSXStyle from "next/dist/shared/lib/styled-jsx";
import _JSXStyle from "styled-jsx/style";
export default (()=><div className={"jsx-768337a97aceabd1"}>
<p className={"jsx-768337a97aceabd1"}>test</p>
......
import _JSXStyle from "next/dist/shared/lib/styled-jsx";
import _JSXStyle from "styled-jsx/style";
export default (()=><div className={"jsx-94239b6d6b42c9b5"}>
<p className={"jsx-94239b6d6b42c9b5"}>test</p>
......
......@@ -16,7 +16,7 @@ type StyledJsxBabelOptions =
// Resolve styled-jsx plugins
function styledJsxOptions(options: StyledJsxBabelOptions) {
options = options || {}
options.styleModule = 'next/dist/shared/lib/styled-jsx'
options.styleModule = 'styled-jsx/style'
if (!Array.isArray(options.plugins)) {
return options
......@@ -185,8 +185,8 @@ export default (
],
[
isTest && options['styled-jsx'] && options['styled-jsx']['babel-test']
? require('styled-jsx/babel-test')
: require('styled-jsx/babel'),
? require('next/dist/styled-jsx/babel-test')
: require('next/dist/styled-jsx/babel'),
styledJsxOptions(options['styled-jsx']),
],
require('./plugins/amp-attributes'),
......
import type { NextConfigComplete } from '../server/config-shared'
import '../server/node-polyfill-fetch'
import loadRequireHook from '../build/webpack/require-hook'
import chalk from 'next/dist/compiled/chalk'
import getGzipSize from 'next/dist/compiled/gzip-size'
import textTable from 'next/dist/compiled/text-table'
......@@ -59,6 +60,8 @@ const fsStat = (file: string) => {
return (fileStats[file] = fileSize(file))
}
loadRequireHook()
export interface PageInfo {
isHybridAmp?: boolean
size: number
......
......@@ -685,6 +685,8 @@ export default async function getBaseWebpackConfig(
'react-dom/server$': `${reactDomDir}/server`,
'react-dom/server.browser$': `${reactDomDir}/server.browser`,
'react-dom/client$': `${reactDomDir}/client`,
'styled-jsx/style$': require.resolve(`next/dist/styled-jsx/style`),
'styled-jsx$': require.resolve(`next/dist/styled-jsx`),
...customAppAliases,
...customErrorAlias,
......@@ -860,11 +862,11 @@ export default async function getBaseWebpackConfig(
const isEsmRequested = dependencyType === 'esm'
const isLocalCallback = (localRes: string) => {
// Makes sure dist/shared and dist/server are not bundled
// Makes sure dist/styled-jsx, dist/shared and dist/server are not bundled
// we need to process shared `router/router` and `dynamic`,
// so that the DefinePlugin can inject process.env values
const isNextExternal =
/next[/\\]dist[/\\](shared|server)[/\\](?!lib[/\\](router[/\\]router|dynamic))/.test(
/next[/\\]dist[/\\](styled-jsx|shared|server)[/\\](?!lib[/\\](router[/\\]router|dynamic))/.test(
localRes
)
......
......@@ -2,145 +2,26 @@
// this is in order for userland plugins to attach to the same webpack instance as next.js
// the individual compiled modules are as defined for the compilation in bundles/webpack/packages/*
const hookPropertyMap = new Map(
[
['webpack', 'next/dist/compiled/webpack/webpack-lib'],
['webpack/package', 'next/dist/compiled/webpack/package'],
['webpack/package.json', 'next/dist/compiled/webpack/package'],
['webpack/lib/webpack', 'next/dist/compiled/webpack/webpack-lib'],
['webpack/lib/webpack.js', 'next/dist/compiled/webpack/webpack-lib'],
[
'webpack/lib/node/NodeEnvironmentPlugin',
'next/dist/compiled/webpack/NodeEnvironmentPlugin',
],
[
'webpack/lib/node/NodeEnvironmentPlugin.js',
'next/dist/compiled/webpack/NodeEnvironmentPlugin',
],
[
'webpack/lib/BasicEvaluatedExpression',
'next/dist/compiled/webpack/BasicEvaluatedExpression',
],
[
'webpack/lib/BasicEvaluatedExpression.js',
'next/dist/compiled/webpack/BasicEvaluatedExpression',
],
[
'webpack/lib/node/NodeTargetPlugin',
'next/dist/compiled/webpack/NodeTargetPlugin',
],
[
'webpack/lib/node/NodeTargetPlugin.js',
'next/dist/compiled/webpack/NodeTargetPlugin',
],
[
'webpack/lib/node/NodeTemplatePlugin',
'next/dist/compiled/webpack/NodeTemplatePlugin',
],
[
'webpack/lib/node/NodeTemplatePlugin.js',
'next/dist/compiled/webpack/NodeTemplatePlugin',
],
[
'webpack/lib/LibraryTemplatePlugin',
'next/dist/compiled/webpack/LibraryTemplatePlugin',
],
[
'webpack/lib/LibraryTemplatePlugin.js',
'next/dist/compiled/webpack/LibraryTemplatePlugin',
],
[
'webpack/lib/SingleEntryPlugin',
'next/dist/compiled/webpack/SingleEntryPlugin',
],
[
'webpack/lib/SingleEntryPlugin.js',
'next/dist/compiled/webpack/SingleEntryPlugin',
],
[
'webpack/lib/optimize/LimitChunkCountPlugin',
'next/dist/compiled/webpack/LimitChunkCountPlugin',
],
[
'webpack/lib/optimize/LimitChunkCountPlugin.js',
'next/dist/compiled/webpack/LimitChunkCountPlugin',
],
[
'webpack/lib/webworker/WebWorkerTemplatePlugin',
'next/dist/compiled/webpack/WebWorkerTemplatePlugin',
],
[
'webpack/lib/webworker/WebWorkerTemplatePlugin.js',
'next/dist/compiled/webpack/WebWorkerTemplatePlugin',
],
[
'webpack/lib/ExternalsPlugin',
'next/dist/compiled/webpack/ExternalsPlugin',
],
[
'webpack/lib/ExternalsPlugin.js',
'next/dist/compiled/webpack/ExternalsPlugin',
],
[
'webpack/lib/web/FetchCompileWasmTemplatePlugin',
'next/dist/compiled/webpack/FetchCompileWasmTemplatePlugin',
],
[
'webpack/lib/web/FetchCompileWasmTemplatePlugin.js',
'next/dist/compiled/webpack/FetchCompileWasmTemplatePlugin',
],
[
'webpack/lib/web/FetchCompileWasmPlugin',
'next/dist/compiled/webpack/FetchCompileWasmPlugin',
],
[
'webpack/lib/web/FetchCompileWasmPlugin.js',
'next/dist/compiled/webpack/FetchCompileWasmPlugin',
],
[
'webpack/lib/web/FetchCompileAsyncWasmPlugin',
'next/dist/compiled/webpack/FetchCompileAsyncWasmPlugin',
],
[
'webpack/lib/web/FetchCompileAsyncWasmPlugin.js',
'next/dist/compiled/webpack/FetchCompileAsyncWasmPlugin',
],
[
'webpack/lib/ModuleFilenameHelpers',
'next/dist/compiled/webpack/ModuleFilenameHelpers',
],
[
'webpack/lib/ModuleFilenameHelpers.js',
'next/dist/compiled/webpack/ModuleFilenameHelpers',
],
['webpack/lib/GraphHelpers', 'next/dist/compiled/webpack/GraphHelpers'],
['webpack/lib/GraphHelpers.js', 'next/dist/compiled/webpack/GraphHelpers'],
['webpack/lib/NormalModule', 'next/dist/compiled/webpack/NormalModule'],
['webpack-sources', 'next/dist/compiled/webpack/sources'],
['webpack-sources/lib', 'next/dist/compiled/webpack/sources'],
['webpack-sources/lib/index', 'next/dist/compiled/webpack/sources'],
['webpack-sources/lib/index.js', 'next/dist/compiled/webpack/sources'],
['@babel/runtime', 'next/dist/compiled/@babel/runtime/package.json'],
[
'@babel/runtime/package.json',
'next/dist/compiled/@babel/runtime/package.json',
],
['node-fetch', 'next/dist/compiled/node-fetch'],
].map(([request, replacement]) => [request, require.resolve(replacement)])
)
export default function loadRequireHook(aliases: [string, string][] = []) {
const hookPropertyMap = new Map(
[
...aliases,
// Use `require.resolve` explicitly to make them statically analyzable
['styled-jsx', require.resolve('next/dist/styled-jsx')],
['styled-jsx/style', require.resolve('next/dist/styled-jsx/style')],
].map(([request, replacement]) => [request, replacement])
)
const mod = require('module')
const resolveFilename = mod._resolveFilename
mod._resolveFilename = function (
request: string,
parent: any,
isMain: boolean,
options: any
) {
const hookResolved = hookPropertyMap.get(request)
if (hookResolved) request = hookResolved
return resolveFilename.call(mod, request, parent, isMain, options)
const mod = require('module')
const resolveFilename = mod._resolveFilename
mod._resolveFilename = function (
request: string,
parent: any,
isMain: boolean,
options: any
) {
const hookResolved = hookPropertyMap.get(request)
if (hookResolved) request = hookResolved
return resolveFilename.call(mod, request, parent, isMain, options)
}
}
// Flag as module for typescript
export {}
......@@ -4,6 +4,10 @@ import type { GetStaticProps } from '../types'
import type { IncomingMessage, ServerResponse } from 'http'
import type { DomainLocale, NextConfigComplete } from '../server/config-shared'
import type { NextParsedUrlQuery } from '../server/request-meta'
import '../server/node-polyfill-fetch'
import loadRequireHook from '../build/webpack/require-hook'
import url from 'url'
import { extname, join, dirname, sep } from 'path'
import { renderToHTML } from '../server/render'
......@@ -15,7 +19,6 @@ import { getRouteMatcher } from '../shared/lib/router/utils/route-matcher'
import { getRouteRegex } from '../shared/lib/router/utils/route-regex'
import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'
import { SERVER_PROPS_EXPORT_ERROR } from '../lib/constants'
import '../server/node-polyfill-fetch'
import { requireFontManifest } from '../server/require'
import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'
import { trace } from '../trace'
......@@ -25,6 +28,7 @@ import RenderResult from '../server/render-result'
import isError from '../lib/is-error'
import { addRequestMeta } from '../server/request-meta'
loadRequireHook()
const envConfig = require('../shared/lib/runtime-config')
;(global as any).__NEXT_DATA__ = {
......
/// <reference types="./types/global" />
/// <reference path="./dist/styled-jsx-types/global.d.ts" />
/// <reference path="./dist/styled-jsx/global.d.ts" />
/// <reference path="./amp.d.ts" />
/// <reference path="./app.d.ts" />
/// <reference path="./config.d.ts" />
......
......@@ -74,7 +74,6 @@
"@swc/helpers": "0.4.3",
"caniuse-lite": "^1.0.30001332",
"postcss": "8.4.14",
"styled-jsx": "5.0.2",
"use-sync-external-store": "1.2.0"
},
"peerDependencies": {
......@@ -258,6 +257,7 @@
"string-hash": "1.1.3",
"string_decoder": "1.3.0",
"strip-ansi": "6.0.0",
"styled-jsx": "5.0.2",
"tar": "6.1.11",
"taskr": "1.1.0",
"terser": "5.14.1",
......
import React from 'react'
import Head from '../shared/lib/head'
import { NextPageContext } from '../shared/lib/utils'
import type { NextPageContext } from '../shared/lib/utils'
const statusCodes: { [code: number]: string } = {
400: 'Bad Request',
......@@ -57,7 +57,7 @@ export default class Error<P = {}> extends React.Component<P & ErrorProps> {
.next-error-h1 {
border-right: 1px solid rgba(0, 0, 0, .3);
}
${
withDarkMode
? `@media (prefers-color-scheme: dark) {
......
......@@ -12,5 +12,136 @@ export function loadWebpackHook() {
// hook the Node.js require so that webpack requires are
// routed to the bundled and now initialized webpack version
require('../build/webpack/require-hook')
require('../build/webpack/require-hook').default(
[
['webpack', 'next/dist/compiled/webpack/webpack-lib'],
['webpack/package', 'next/dist/compiled/webpack/package'],
['webpack/package.json', 'next/dist/compiled/webpack/package'],
['webpack/lib/webpack', 'next/dist/compiled/webpack/webpack-lib'],
['webpack/lib/webpack.js', 'next/dist/compiled/webpack/webpack-lib'],
[
'webpack/lib/node/NodeEnvironmentPlugin',
'next/dist/compiled/webpack/NodeEnvironmentPlugin',
],
[
'webpack/lib/node/NodeEnvironmentPlugin.js',
'next/dist/compiled/webpack/NodeEnvironmentPlugin',
],
[
'webpack/lib/BasicEvaluatedExpression',
'next/dist/compiled/webpack/BasicEvaluatedExpression',
],
[
'webpack/lib/BasicEvaluatedExpression.js',
'next/dist/compiled/webpack/BasicEvaluatedExpression',
],
[
'webpack/lib/node/NodeTargetPlugin',
'next/dist/compiled/webpack/NodeTargetPlugin',
],
[
'webpack/lib/node/NodeTargetPlugin.js',
'next/dist/compiled/webpack/NodeTargetPlugin',
],
[
'webpack/lib/node/NodeTemplatePlugin',
'next/dist/compiled/webpack/NodeTemplatePlugin',
],
[
'webpack/lib/node/NodeTemplatePlugin.js',
'next/dist/compiled/webpack/NodeTemplatePlugin',
],
[
'webpack/lib/LibraryTemplatePlugin',
'next/dist/compiled/webpack/LibraryTemplatePlugin',
],
[
'webpack/lib/LibraryTemplatePlugin.js',
'next/dist/compiled/webpack/LibraryTemplatePlugin',
],
[
'webpack/lib/SingleEntryPlugin',
'next/dist/compiled/webpack/SingleEntryPlugin',
],
[
'webpack/lib/SingleEntryPlugin.js',
'next/dist/compiled/webpack/SingleEntryPlugin',
],
[
'webpack/lib/optimize/LimitChunkCountPlugin',
'next/dist/compiled/webpack/LimitChunkCountPlugin',
],
[
'webpack/lib/optimize/LimitChunkCountPlugin.js',
'next/dist/compiled/webpack/LimitChunkCountPlugin',
],
[
'webpack/lib/webworker/WebWorkerTemplatePlugin',
'next/dist/compiled/webpack/WebWorkerTemplatePlugin',
],
[
'webpack/lib/webworker/WebWorkerTemplatePlugin.js',
'next/dist/compiled/webpack/WebWorkerTemplatePlugin',
],
[
'webpack/lib/ExternalsPlugin',
'next/dist/compiled/webpack/ExternalsPlugin',
],
[
'webpack/lib/ExternalsPlugin.js',
'next/dist/compiled/webpack/ExternalsPlugin',
],
[
'webpack/lib/web/FetchCompileWasmTemplatePlugin',
'next/dist/compiled/webpack/FetchCompileWasmTemplatePlugin',
],
[
'webpack/lib/web/FetchCompileWasmTemplatePlugin.js',
'next/dist/compiled/webpack/FetchCompileWasmTemplatePlugin',
],
[
'webpack/lib/web/FetchCompileWasmPlugin',
'next/dist/compiled/webpack/FetchCompileWasmPlugin',
],
[
'webpack/lib/web/FetchCompileWasmPlugin.js',
'next/dist/compiled/webpack/FetchCompileWasmPlugin',
],
[
'webpack/lib/web/FetchCompileAsyncWasmPlugin',
'next/dist/compiled/webpack/FetchCompileAsyncWasmPlugin',
],
[
'webpack/lib/web/FetchCompileAsyncWasmPlugin.js',
'next/dist/compiled/webpack/FetchCompileAsyncWasmPlugin',
],
[
'webpack/lib/ModuleFilenameHelpers',
'next/dist/compiled/webpack/ModuleFilenameHelpers',
],
[
'webpack/lib/ModuleFilenameHelpers.js',
'next/dist/compiled/webpack/ModuleFilenameHelpers',
],
['webpack/lib/GraphHelpers', 'next/dist/compiled/webpack/GraphHelpers'],
[
'webpack/lib/GraphHelpers.js',
'next/dist/compiled/webpack/GraphHelpers',
],
['webpack/lib/NormalModule', 'next/dist/compiled/webpack/NormalModule'],
['webpack-sources', 'next/dist/compiled/webpack/sources'],
['webpack-sources/lib', 'next/dist/compiled/webpack/sources'],
['webpack-sources/lib/index', 'next/dist/compiled/webpack/sources'],
['webpack-sources/lib/index.js', 'next/dist/compiled/webpack/sources'],
['@babel/runtime', 'next/dist/compiled/@babel/runtime/package.json'],
[
'@babel/runtime/package.json',
'next/dist/compiled/@babel/runtime/package.json',
],
['node-fetch', 'next/dist/compiled/node-fetch'],
].map(
// Use dynamic require.resolve to avoid statically analyzable since they're only for build time
([request, replacement]) => [request, require.resolve(replacement)]
)
)
}
......@@ -726,7 +726,7 @@ export default async function loadConfig(
customConfig?: object | null
): Promise<NextConfigComplete> {
await loadEnvConfig(dir, phase === PHASE_DEVELOPMENT_SERVER, Log)
await loadWebpackHook()
loadWebpackHook()
let configFileName = 'next.config.js'
......
......@@ -27,7 +27,6 @@ import fs from 'fs'
import { join, relative, resolve, sep } from 'path'
import { IncomingMessage, ServerResponse } from 'http'
import { addRequestMeta, getRequestMeta } from './request-meta'
import {
PAGES_MANIFEST,
BUILD_ID_FILE,
......@@ -56,6 +55,7 @@ import { RenderOpts, renderToHTML } from './render'
import { renderToHTMLOrFlight as appRenderToHTMLOrFlight } from './app-render'
import { ParsedUrl, parseUrl } from '../shared/lib/router/utils/parse-url'
import * as Log from '../build/output/log'
import loadRequireHook from '../build/webpack/require-hook'
import BaseServer, {
Options,
......@@ -90,6 +90,8 @@ if (shouldUseReactRoot) {
;(process.env as any).__NEXT_REACT_ROOT = 'true'
}
loadRequireHook()
export * from './base-server'
type ExpressMiddleware = (
......
......@@ -28,7 +28,7 @@ import type { UnwrapPromise } from '../lib/coalesced-function'
import type { ReactReadableStream } from './node-web-streams-helper'
import React from 'react'
import { StyleRegistry, createStyleRegistry } from 'styled-jsx'
import { StyleRegistry, createStyleRegistry } from 'next/dist/styled-jsx'
import {
GSP_NO_RETURNED_VALUE,
GSSP_COMPONENT_MEMBER_ERROR,
......
export default function JSXStyle(props: any): null
module.exports = require('styled-jsx/style')
......@@ -43,13 +43,16 @@ export async function copy_regenerator_runtime(task, opts) {
}
// eslint-disable-next-line camelcase
export async function copy_styled_jsx_types(task, opts) {
export async function copy_styled_jsx_assets(task, opts) {
// we copy the styled-jsx types so that we can reference them
// in the next-env.d.ts file so it doesn't matter if the styled-jsx
// package is hoisted out of Next.js' node_modules or not
const styledJsxPath = dirname(require.resolve('styled-jsx/package.json'))
const typeFiles = glob.sync('*.d.ts', { cwd: styledJsxPath })
const outputDir = join(__dirname, 'dist/styled-jsx-types')
const jsFiles = glob.sync('**/{index,style,babel,babel-test}.js', {
cwd: styledJsxPath,
})
const outputDir = join(__dirname, 'dist/styled-jsx')
let typeReferences = ``
await fs.ensureDir(outputDir)
......@@ -59,19 +62,31 @@ export async function copy_styled_jsx_types(task, opts) {
const content = await fs.readFile(join(styledJsxPath, file), 'utf8')
const exportsIndex = content.indexOf('export')
await fs.writeFile(
join(outputDir, file),
let replacedContent =
`${content.substring(0, exportsIndex)}\n` +
`declare module 'styled-jsx${
file === 'index.d.ts' ? '' : '/' + fileNoExt
}' {
`declare module 'styled-jsx${
file === 'index.d.ts' ? '' : '/' + fileNoExt
}' {
${content.substring(exportsIndex)}
}`
)
if (file === 'index.d.ts') {
replacedContent = replacedContent
.replace(/export function StyleRegistry/g, 'export function IRegistry')
.replace(/StyleRegistry/g, 'IStyleRegistry')
.replace(/IRegistry/g, 'Registry')
}
await fs.writeFile(join(outputDir, file), replacedContent)
typeReferences += `/// <reference types="./${fileNoExt}" />\n`
}
await fs.writeFile(join(outputDir, 'global.d.ts'), typeReferences)
for (const file of jsFiles) {
const content = await fs.readFile(join(styledJsxPath, file), 'utf8')
const distFile = join(outputDir, file)
await fs.ensureDir(dirname(distFile))
await fs.writeFile(distFile, content)
}
}
const externals = {
......@@ -1950,7 +1965,7 @@ export async function compile(task, opts) {
// we compile this each time so that fresh runtime data is pulled
// before each publish
'ncc_amp_optimizer',
'copy_styled_jsx_types',
'copy_styled_jsx_assets',
],
opts
)
......
......@@ -18,6 +18,11 @@ declare module 'next/dist/compiled/@next/react-refresh-utils/dist/ReactRefreshWe
export = m
}
declare module 'next/dist/styled-jsx' {
import m from 'styled-jsx'
export = m
}
declare module 'next/dist/compiled/node-html-parser' {
export * from 'node-html-parser'
}
......
......@@ -155,7 +155,6 @@ importers:
semver: 7.3.7
shell-quote: 1.7.3
styled-components: 5.3.3
styled-jsx: link:packages/next/node_modules/styled-jsx
styled-jsx-plugin-postcss: 3.0.2
tailwindcss: 1.1.3
taskr: 1.1.0
......@@ -310,7 +309,6 @@ importers:
semver: 7.3.7
shell-quote: 1.7.3
styled-components: 5.3.3_vtcxgy2wlmese7djxl6h7ok674
styled-jsx: link:packages/next/node_modules/styled-jsx
styled-jsx-plugin-postcss: 3.0.2
tailwindcss: 1.1.3
taskr: 1.1.0
......@@ -588,7 +586,6 @@ importers:
'@swc/helpers': 0.4.3
caniuse-lite: 1.0.30001332
postcss: 8.4.14
styled-jsx: 5.0.2_@babel+core@7.18.0
use-sync-external-store: 1.2.0
devDependencies:
'@ampproject/toolbox-optimizer': 2.8.3
......@@ -753,6 +750,7 @@ importers:
string_decoder: 1.3.0
string-hash: 1.1.3
strip-ansi: 6.0.0
styled-jsx: 5.0.2_@babel+core@7.18.0
tar: 6.1.11
taskr: 1.1.0
terser: 5.14.1
......@@ -10456,6 +10454,7 @@ packages:
eslint: ^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0-0
dependencies:
eslint: 7.32.0
dev: false
/eslint-plugin-react/7.23.2_eslint@7.24.0:
resolution: {integrity: sha512-AfjgFQB+nYszudkxRkTFu0UR1zEQig0ArVMPloKhxwlwkzaw/fBiH0QWcBBhZONlXqQC51+nfqFrkn4EzHcGBw==}
......@@ -20575,7 +20574,7 @@ packages:
optional: true
dependencies:
'@babel/core': 7.18.0
dev: false
dev: true
/stylehacks/4.0.3:
resolution: {integrity: sha512-7GlLk9JwlElY4Y6a/rmbH2MhVlTyVmiJd1PfTCqFaIBEGMYNsrO/v3SeGTdhBThLg4Z+NbOk/qFMwCa+J+3p/g==}
......
......@@ -41,7 +41,6 @@ describe('app dir - react server components', () => {
'next.config.js': new FileRef(path.join(appDir, 'next.config.js')),
},
dependencies: {
'styled-jsx': 'latest',
'styled-components': '6.0.0-alpha.5',
react: 'experimental',
'react-dom': 'experimental',
......@@ -327,7 +326,8 @@ describe('app dir - react server components', () => {
const head = getNodeBySelector(html, 'head').html()
// from styled-jsx
expect(head).toMatch(/{color:(\s*)purple;?}/)
expect(head).toMatch(/{color:(\s*)purple;?}/) // styled-jsx/style
expect(head).toMatch(/{color:(\s*)hotpink;?}/) // styled-jsx/css
// from styled-components
expect(head).toMatch(/{color:(\s*)blue;?}/)
......
import css from 'styled-jsx/css'
const buttonStyles = css`
button {
color: hotpink;
}
`
export default function Comp() {
return (
<div>
......@@ -10,9 +18,11 @@ export default function Comp() {
border: 2px solid purple;
}
`}</style>
<style jsx>{buttonStyles}</style>
<div className="box">
<h3>styled-jsx</h3>
<p>This area is rendered by styled-jsx</p>
<button>click</button>
</div>
</div>
)
......
......@@ -20,12 +20,10 @@ export default function RootStyleRegistry({ children }) {
}
useFlushEffects(() => {
const effects = styledComponentsFlushEffect()
return (
<>
{styledJsxFlushEffect()}
{effects}
{styledComponentsFlushEffect()}
</>
)
})
......
auto-install-peers=true
strict-peer-dependencies=false
Object.defineProperty(exports, '__esModule', { value: true })
function _interopDefault(ex) {
return ex && typeof ex === 'object' && 'default' in ex ? ex['default'] : ex
}
var _JSXStyle = _interopDefault(require('styled-jsx/style'))
var React = require('react')
function Button() {
return React.createElement(
'button',
{
className: 'jsx-451104437',
},
'hello',
React.createElement(
_JSXStyle,
{
id: '451104437',
},
'.jsx-451104437{color:cyan;}\n/*# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIkJ1dHRvbi50c3giXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBTWtCLEFBRW1CLFVBQ1oiLCJmaWxlIjoiQnV0dG9uLnRzeCIsInNvdXJjZXNDb250ZW50IjpbImltcG9ydCAqIGFzIFJlYWN0IGZyb20gJ3JlYWN0JztcblxuZXhwb3J0IGRlZmF1bHQgZnVuY3Rpb24gQnV0dG9uKCkge1xuICByZXR1cm4gKFxuICAgIDxidXR0b24+XG4gICAgICBoZWxsb1xuICAgICAgPHN0eWxlIGpzeD57YFxuICAgICAgICBjb2xybzogcmVkO1xuICAgICAgYH08L3N0eWxlPlxuICAgIDwvYnV0dG9uPlxuICApO1xufVxuIl19 */\n/*@ sourceURL=Button.tsx */'
)
)
}
/**
* @class ExampleComponent
*/
exports.Button = Button
......@@ -2,11 +2,11 @@ import { Button } from 'my-comps/button'
export const config = { amp: true }
const Index = () => (
<>
<p>Hello world</p>
<Button>Click me</Button>
</>
)
export default Index
export default function page() {
return (
<>
<p>Hello world</p>
<Button>Click me</Button>
</>
)
}
import { Button } from 'my-comps/button'
export default function Page() {
return (
<div>
<style jsx>{'p { color: red; }'}</style>
<p>hello world</p>
<Button>Click me</Button>
</div>
)
}
......@@ -2,35 +2,67 @@ import path from 'path'
import { createNext, FileRef } from 'e2e-utils'
import { NextInstance } from 'test/lib/next-modes/base'
import { renderViaHTTP } from 'next-test-utils'
import cheerio from 'cheerio'
import webdriver from 'next-webdriver'
const appDir = path.join(__dirname, 'app')
function runTest(packageManager?: string) {
describe(`styled-jsx${packageManager ? ' ' + packageManager : ''}`, () => {
function runTest() {
describe(`styled-jsx`, () => {
let next: NextInstance
beforeAll(async () => {
next = await createNext({
files: {
node_modules_bak: new FileRef(path.join(appDir, 'node_modules_bak')),
pages: new FileRef(path.join(appDir, 'pages')),
'.npmrc': new FileRef(path.join(appDir, '.npmrc')),
},
...(packageManager
? {
installCommand: `npx ${packageManager} install`,
}
: {}),
packageJson: {
scripts: {
setup: `cp -r ./node_modules_bak/my-comps ./node_modules;`,
build: `yarn setup && next build`,
dev: `yarn setup && next dev`,
start: 'next start',
},
},
dependencies: {
'styled-jsx': '5.0.0', // styled-jsx on user side
},
startCommand: 'yarn ' + ((global as any).isNextDev ? 'dev' : 'start'),
buildCommand: `yarn build`,
})
})
afterAll(() => next.destroy())
it('should contain styled-jsx styles in html', async () => {
it('should contain styled-jsx styles during SSR', async () => {
const html = await renderViaHTTP(next.url, '/')
const $ = cheerio.load(html)
expect($('html').text()).toMatch(/color:(\s)*red/)
expect(html).toMatch(/color:.*?red/)
expect(html).toMatch(/color:.*?cyan/)
})
it('should render styles during CSR', async () => {
const browser = await webdriver(next.url, '/')
const color = await browser.eval(
`getComputedStyle(document.querySelector('button')).color`
)
expect(color).toMatch('0, 255, 255')
})
it('should render styles during CSR (AMP)', async () => {
const browser = await webdriver(next.url, '/amp')
const color = await browser.eval(
`getComputedStyle(document.querySelector('button')).color`
)
expect(color).toMatch('0, 255, 255')
})
it('should render styles during SSR (AMP)', async () => {
const html = await renderViaHTTP(next.url, '/amp')
expect(html).toMatch(/color:.*?cyan/)
})
})
}
runTest()
runTest('pnpm')
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var _JSXStyle = _interopDefault(require('styled-jsx/style'));
var React = require('react');
function Button() {
return React.createElement("button", {
className: "jsx-451104437"
}, "hello", React.createElement(_JSXStyle, {
id: "451104437"
}, ".jsx-451104437{color:cyan;}\n/*# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIkJ1dHRvbi50c3giXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBTWtCLEFBRW1CLFVBQ1oiLCJmaWxlIjoiQnV0dG9uLnRzeCIsInNvdXJjZXNDb250ZW50IjpbImltcG9ydCAqIGFzIFJlYWN0IGZyb20gJ3JlYWN0JztcblxuZXhwb3J0IGRlZmF1bHQgZnVuY3Rpb24gQnV0dG9uKCkge1xuICByZXR1cm4gKFxuICAgIDxidXR0b24+XG4gICAgICBoZWxsb1xuICAgICAgPHN0eWxlIGpzeD57YFxuICAgICAgICBjb2xybzogcmVkO1xuICAgICAgYH08L3N0eWxlPlxuICAgIDwvYnV0dG9uPlxuICApO1xufVxuIl19 */\n/*@ sourceURL=Button.tsx */"));
}
/**
* @class ExampleComponent
*/
exports.Button = Button;
\ No newline at end of file
{
"name": "my-comps",
"version": "1.0.0",
"main": "index.js",
"license": "MIT"
}
{
"name": "styled-jsx-module",
"version": "1.0.0",
"main": "index.js",
"license": "MIT"
}
import { Button } from 'my-comps/button'
const Index = () => (
<>
<p>Hello world</p>
<Button>Click me</Button>
</>
)
export default Index
/* eslint-env jest */
import { join } from 'path'
import webdriver from 'next-webdriver'
import {
killApp,
findPort,
nextStart,
nextBuild,
launchApp,
renderViaHTTP,
} from 'next-test-utils'
const appDir = join(__dirname, '../app')
let appPort
let app
function runTests() {
it('should render styles during CSR', async () => {
const browser = await webdriver(appPort, '/')
const color = await browser.eval(
`getComputedStyle(document.querySelector('button')).color`
)
expect(color).toMatch('0, 255, 255')
})
it('should render styles during CSR (AMP)', async () => {
const browser = await webdriver(appPort, '/amp')
const color = await browser.eval(
`getComputedStyle(document.querySelector('button')).color`
)
expect(color).toMatch('0, 255, 255')
})
it('should render styles during SSR', async () => {
const html = await renderViaHTTP(appPort, '/')
expect(html).toMatch(/color:.*?cyan/)
})
it('should render styles during SSR (AMP)', async () => {
const html = await renderViaHTTP(appPort, '/amp')
expect(html).toMatch(/color:.*?cyan/)
})
}
describe('styled-jsx using in node_modules', () => {
describe('Production', () => {
beforeAll(async () => {
await nextBuild(appDir)
appPort = await findPort()
app = await nextStart(appDir, appPort)
})
afterAll(() => killApp(app))
runTests()
})
describe('Development', () => {
beforeAll(async () => {
appPort = await findPort()
app = await launchApp(appDir, appPort)
})
afterAll(() => killApp(app))
runTests()
})
})
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment