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