Unverified Commit 2e16d02f authored by LongYinan's avatar LongYinan Committed by GitHub

SWC emotion transform plugin (#34687)

parent 6611bfd3
...@@ -97,7 +97,7 @@ jobs: ...@@ -97,7 +97,7 @@ jobs:
if: ${{needs.build.outputs.docsChange != 'docs only change'}} if: ${{needs.build.outputs.docsChange != 'docs only change'}}
with: with:
profile: minimal profile: minimal
toolchain: nightly-2021-11-15 toolchain: nightly-2022-02-23
components: rustfmt, clippy components: rustfmt, clippy
- name: Cache cargo registry - name: Cache cargo registry
...@@ -732,7 +732,7 @@ jobs: ...@@ -732,7 +732,7 @@ jobs:
if: ${{ steps.docs-change.outputs.DOCS_CHANGE != 'docs only change' }} if: ${{ steps.docs-change.outputs.DOCS_CHANGE != 'docs only change' }}
with: with:
profile: minimal profile: minimal
toolchain: nightly-2021-11-15 toolchain: nightly-2022-02-23
- name: Cache cargo registry - name: Cache cargo registry
uses: actions/cache@v2 uses: actions/cache@v2
...@@ -811,7 +811,7 @@ jobs: ...@@ -811,7 +811,7 @@ jobs:
if: ${{ steps.docs-change.outputs.DOCS_CHANGE != 'docs only change' }} if: ${{ steps.docs-change.outputs.DOCS_CHANGE != 'docs only change' }}
uses: actions-rs/toolchain@v1 uses: actions-rs/toolchain@v1
with: with:
toolchain: nightly-2021-11-15 toolchain: nightly-2022-02-23
profile: minimal profile: minimal
- run: cd packages/next-swc && cargo test - run: cd packages/next-swc && cargo test
if: ${{ steps.docs-change.outputs.DOCS_CHANGE != 'docs only change' }} if: ${{ steps.docs-change.outputs.DOCS_CHANGE != 'docs only change' }}
...@@ -889,8 +889,8 @@ jobs: ...@@ -889,8 +889,8 @@ jobs:
# Node.js in Baidu need to compatible with `GLIBC_2.12` # Node.js in Baidu need to compatible with `GLIBC_2.12`
build: >- build: >-
set -e && set -e &&
rustup toolchain install nightly-2021-11-15 && rustup toolchain install nightly-2022-02-23 &&
rustup default nightly-2021-11-15 && rustup default nightly-2022-02-23 &&
rustup target add x86_64-unknown-linux-gnu && rustup target add x86_64-unknown-linux-gnu &&
npm i -g @napi-rs/cli@2.4.4 turbo@1.0.28 && npm i -g @napi-rs/cli@2.4.4 turbo@1.0.28 &&
turbo run build-native --cache-dir=".turbo" -- --release --target x86_64-unknown-linux-gnu --zig --zig-abi-suffix 2.12 && turbo run build-native --cache-dir=".turbo" -- --release --target x86_64-unknown-linux-gnu --zig --zig-abi-suffix 2.12 &&
...@@ -900,8 +900,8 @@ jobs: ...@@ -900,8 +900,8 @@ jobs:
docker: ghcr.io/napi-rs/napi-rs/nodejs-rust:lts-alpine docker: ghcr.io/napi-rs/napi-rs/nodejs-rust:lts-alpine
build: >- build: >-
set -e && set -e &&
rustup toolchain install nightly-2021-11-15 && rustup toolchain install nightly-2022-02-23 &&
rustup default nightly-2021-11-15 && rustup default nightly-2022-02-23 &&
rustup target add x86_64-unknown-linux-musl && rustup target add x86_64-unknown-linux-musl &&
npm i -g @napi-rs/cli@2.4.4 turbo@1.0.28 && npm i -g @napi-rs/cli@2.4.4 turbo@1.0.28 &&
turbo run build-native --cache-dir=".turbo" -- --release --target x86_64-unknown-linux-musl && turbo run build-native --cache-dir=".turbo" -- --release --target x86_64-unknown-linux-musl &&
...@@ -922,8 +922,8 @@ jobs: ...@@ -922,8 +922,8 @@ jobs:
docker: ghcr.io/napi-rs/napi-rs/nodejs-rust:lts-alpine-zig docker: ghcr.io/napi-rs/napi-rs/nodejs-rust:lts-alpine-zig
build: >- build: >-
set -e && set -e &&
rustup toolchain install nightly-2021-11-15 && rustup toolchain install nightly-2022-02-23 &&
rustup default nightly-2021-11-15 && rustup default nightly-2022-02-23 &&
rustup target add aarch64-unknown-linux-gnu && rustup target add aarch64-unknown-linux-gnu &&
npm i -g @napi-rs/cli@2.4.4 turbo@1.0.28 && npm i -g @napi-rs/cli@2.4.4 turbo@1.0.28 &&
turbo run build-native --cache-dir=".turbo" -- --release --target aarch64-unknown-linux-gnu --zig --zig-abi-suffix 2.12 && turbo run build-native --cache-dir=".turbo" -- --release --target aarch64-unknown-linux-gnu --zig --zig-abi-suffix 2.12 &&
...@@ -963,8 +963,8 @@ jobs: ...@@ -963,8 +963,8 @@ jobs:
build: >- build: >-
set -e && set -e &&
npm i -g @napi-rs/cli@2.4.4 turbo@1.0.28 && npm i -g @napi-rs/cli@2.4.4 turbo@1.0.28 &&
rustup toolchain install nightly-2021-11-15 && rustup toolchain install nightly-2022-02-23 &&
rustup default nightly-2021-11-15 && rustup default nightly-2022-02-23 &&
rustup target add aarch64-unknown-linux-musl && rustup target add aarch64-unknown-linux-musl &&
turbo run build-native --cache-dir=".turbo" -- --release --target aarch64-unknown-linux-musl && turbo run build-native --cache-dir=".turbo" -- --release --target aarch64-unknown-linux-musl &&
llvm-strip -x packages/next-swc/native/next-swc.*.node llvm-strip -x packages/next-swc/native/next-swc.*.node
...@@ -1030,7 +1030,7 @@ jobs: ...@@ -1030,7 +1030,7 @@ jobs:
with: with:
profile: minimal profile: minimal
override: true override: true
toolchain: nightly-2021-11-15 toolchain: nightly-2022-02-23
target: ${{ matrix.settings.target }} target: ${{ matrix.settings.target }}
- name: Cache cargo registry - name: Cache cargo registry
...@@ -1092,7 +1092,7 @@ jobs: ...@@ -1092,7 +1092,7 @@ jobs:
uses: actions-rs/toolchain@v1 uses: actions-rs/toolchain@v1
with: with:
profile: minimal profile: minimal
toolchain: nightly-2021-11-15 toolchain: nightly-2022-02-23
override: true override: true
target: wasm32-unknown-unknown target: wasm32-unknown-unknown
...@@ -1148,7 +1148,7 @@ jobs: ...@@ -1148,7 +1148,7 @@ jobs:
uses: actions-rs/toolchain@v1 uses: actions-rs/toolchain@v1
with: with:
profile: minimal profile: minimal
toolchain: nightly-2021-11-15 toolchain: nightly-2022-02-23
override: true override: true
target: wasm32-unknown-unknown target: wasm32-unknown-unknown
......
...@@ -189,6 +189,36 @@ First, update to the latest version of Next.js: `npm install next@latest`. Then, ...@@ -189,6 +189,36 @@ First, update to the latest version of Next.js: `npm install next@latest`. Then,
## Experimental Features ## Experimental Features
### Emotion
We're working to port `@emotion/babel-plugin` to the Next.js Compiler.
First, update to the latest version of Next.js: `npm install next@latest`. Then, update your `next.config.js` file:
```js
// next.config.js
module.exports = {
experimental: {
emotion: boolean | {
// default is true. It will be disabled when build type is production.
sourceMap?: boolean,
// default is 'dev-only'.
autoLabel?: 'never' | 'dev-only' | 'always',
// default is '[local]'.
// Allowed values: `[local]` `[filename]` and `[dirname]`
// This option only works when autoLabel is set to 'dev-only' or 'always'.
// It allows you to define the format of the resulting label.
// The format is defined via string where variable parts are enclosed in square brackets [].
// For example labelFormat: "my-classname--[local]", where [local] will be replaced with the name of the variable the result is assigned to.
labelFormat?: string,
},
},
}
```
Only `importMap` in `@emotion/babel-plugin` is not supported for now.
### Minification ### Minification
You can opt-in to using the Next.js compiler for minification. This is 7x faster than Terser. You can opt-in to using the Next.js compiler for minification. This is 7x faster than Terser.
......
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# local env files
.env.local
.env.development.local
.env.test.local
.env.production.local
# vercel
.vercel
# Emotion Example
Extract and inline critical css with
[@emotion/css](https://github.com/emotion-js/emotion/tree/master/packages/css),
[@emotion/server](https://github.com/emotion-js/emotion/tree/master/packages/server),
[@emotion/react](https://github.com/emotion-js/emotion/tree/master/packages/react),
and [@emotion/styled](https://github.com/emotion-js/emotion/tree/master/packages/styled).
## Preview
Preview the example live on [StackBlitz](http://stackblitz.com/):
[![Open in StackBlitz](https://developer.stackblitz.com/img/open_in_stackblitz.svg)](https://stackblitz.com/github/vercel/next.js/tree/canary/examples/with-emotion)
## Deploy your own
Deploy the example using [Vercel](https://vercel.com?utm_source=github&utm_medium=readme&utm_campaign=next-example):
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/git/external?repository-url=https://github.com/vercel/next.js/tree/canary/examples/with-emotion&project-name=with-emotion&repository-name=with-emotion)
## How to use
Execute [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init) or [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/) to bootstrap the example:
```bash
npx create-next-app --example with-emotion with-emotion-app
# or
yarn create next-app --example with-emotion with-emotion-app
```
Deploy it to the cloud with [Vercel](https://vercel.com/new?utm_source=github&utm_medium=readme&utm_campaign=next-example) ([Documentation](https://nextjs.org/docs/deployment)).
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
experimental: {
emotion: true,
},
}
module.exports = nextConfig
{
"private": true,
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
},
"dependencies": {
"@emotion/react": "11.8.1",
"@emotion/styled": "11.8.1",
"next": "latest",
"react": "17.0.2",
"react-dom": "17.0.2"
}
}
import createCache from '@emotion/cache'
import { CacheProvider } from '@emotion/react'
import { globalStyles } from '../shared/styles'
const cache = createCache({ key: 'next' })
const App = ({ Component, pageProps }) => (
<CacheProvider value={cache}>
{globalStyles}
<Component {...pageProps} />
</CacheProvider>
)
export default App
import { css } from '@emotion/react'
import { Animated, Basic, bounce, Combined, Pink } from '../shared/styles'
const Home = () => (
<div
css={css`
display: flex;
flex-direction: column;
`}
>
<Basic>Cool Styles</Basic>
<Pink>Pink text</Pink>
<Combined>
With <code>:hover</code>.
</Combined>
<Animated animation={bounce}>Let's bounce.</Animated>
</div>
)
export default Home
import { css, Global, keyframes } from '@emotion/react'
import styled from '@emotion/styled'
export const globalStyles = (
<Global
styles={css`
html,
body {
padding: 3rem 1rem;
margin: 0;
background: papayawhip;
min-height: 100%;
font-family: Helvetica, Arial, sans-serif;
font-size: 24px;
}
`}
/>
)
export const basicStyles = css({
backgroundColor: 'white',
color: 'cornflowerblue',
border: '1px solid lightgreen',
borderRight: 'none',
borderBottom: 'none',
boxShadow: '5px 5px 0 0 lightgreen, 10px 10px 0 0 lightyellow',
transition: 'all 0.1s linear',
margin: '3rem 0',
padding: '1rem 0.5rem',
})
export const hoverStyles = css`
&:hover {
color: white;
background-color: lightgray;
border-color: aqua;
box-shadow: -15px -15px 0 0 aqua, -30px -30px 0 0 cornflowerblue;
}
`
export const bounce = keyframes`
from {
transform: scale(1.01);
}
to {
transform: scale(0.99);
}
`
export const Basic = styled.div`
${basicStyles};
`
export const Combined = styled.div`
${basicStyles};
${hoverStyles};
& code {
background-color: linen;
}
`
export const Pink = styled.div(basicStyles, {
color: 'hotpink',
})
export const Animated = styled.div`
${basicStyles};
${hoverStyles};
& code {
background-color: linen;
}
animation: ${({ animation }) => animation} 0.2s infinite ease-in-out alternate;
`
This diff is collapsed.
...@@ -7,27 +7,30 @@ version = "0.0.0" ...@@ -7,27 +7,30 @@ version = "0.0.0"
crate-type = ["cdylib", "rlib"] crate-type = ["cdylib", "rlib"]
[dependencies] [dependencies]
base64 = "0.13"
byteorder = "1"
chrono = "0.4" chrono = "0.4"
once_cell = "1.8.0"
easy-error = "1.0.0" easy-error = "1.0.0"
either = "1" either = "1"
fxhash = "0.2.1" fxhash = "0.2.1"
once_cell = "1.8.0"
pathdiff = "0.2.0" pathdiff = "0.2.0"
radix_fmt = "1"
regex = "1.5"
serde = "1" serde = "1"
serde_json = "1" serde_json = "1"
styled_components = "0.18.0" styled_components = "0.19.0"
swc = "0.146.0" swc = "0.150.1"
swc_atoms = "0.2.7" swc_atoms = "0.2.9"
swc_common = { version = "0.17.11", features = ["concurrent", "sourcemap"] } swc_common = {version = "0.17.15", features = ["concurrent", "sourcemap"]}
swc_css = "0.98.0" swc_css = "0.100.0"
swc_ecma_loader = { version = "0.29.0", features = ["node", "lru"] } swc_ecma_loader = {version = "0.29.0", features = ["node", "lru"]}
swc_ecmascript = { version = "0.130.0", features = ["codegen", "minifier", "optimization", "parser", "react", "transforms", "typescript", "utils", "visit"] } swc_ecmascript = {version = "0.132.0", features = ["codegen", "minifier", "optimization", "parser", "react", "transforms", "typescript", "utils", "visit"]}
swc_node_base = "0.5.1" swc_node_base = "0.5.1"
swc_stylis = "0.94.3" swc_stylis = "0.96.1"
tracing = {version = "0.1.28", features = ["release_max_level_off"]} tracing = {version = "0.1.28", features = ["release_max_level_off"]}
regex = "1.5"
[dev-dependencies] [dev-dependencies]
swc_ecma_transforms_testing = "0.68.0" swc_ecma_transforms_testing = "0.69.0"
testing = "0.18.1" testing = "0.18.1"
walkdir = "2.3.2" walkdir = "2.3.2"
// Ported from https://github.com/aappleby/smhasher/blob/61a0530f28277f2e850bfc39600ce61d02b518de/src/MurmurHash2.cpp#L37-L86
use byteorder::{ByteOrder, LittleEndian};
const M: u32 = 0x5bd1_e995;
pub(crate) fn murmurhash2(key: &[u8], initial_state: u32) -> u32 {
let mut h: u32 = initial_state;
let mut four_bytes_chunks = key.chunks_exact(4);
for chunk in four_bytes_chunks.by_ref() {
let mut k: u32 = LittleEndian::read_u32(chunk);
k = k.wrapping_mul(M);
k ^= k >> 24;
h = k.wrapping_mul(M) ^ h.wrapping_mul(M);
}
let remainder = four_bytes_chunks.remainder();
// Handle the last few bytes of the input array
match remainder.len() {
3 => {
h ^= u32::from(remainder[2]) << 16;
}
2 => {
h ^= u32::from(remainder[1]) << 8;
}
1 => {
h ^= u32::from(remainder[0]);
h = h.wrapping_mul(M);
}
_ => {}
}
h ^= h >> 13;
h = h.wrapping_mul(M);
h ^ (h >> 15)
}
#[cfg(test)]
mod test {
use super::murmurhash2;
#[test]
fn test_murmur2() {
let s1 = "abcdef";
let s2 = "abcdeg";
for i in 0..5 {
assert_eq!(
murmurhash2(&s1[i..5].as_bytes(), 0),
murmurhash2(&s2[i..5].as_bytes(), 0)
);
}
}
#[test]
fn verify_hash() {
assert_eq!(
murmurhash2("something".as_bytes(), 0),
u32::from_str_radix("crsxd7", 36).unwrap()
);
}
}
This diff is collapsed.
...@@ -36,8 +36,9 @@ use std::cell::RefCell; ...@@ -36,8 +36,9 @@ use std::cell::RefCell;
use std::rc::Rc; use std::rc::Rc;
use std::{path::PathBuf, sync::Arc}; use std::{path::PathBuf, sync::Arc};
use swc::config::ModuleConfig; use swc::config::ModuleConfig;
use swc_common::comments::Comments;
use swc_common::{self, chain, pass::Optional}; use swc_common::{self, chain, pass::Optional};
use swc_common::{SourceFile, SourceMap}; use swc_common::{FileName, SourceFile, SourceMap};
use swc_ecmascript::ast::EsVersion; use swc_ecmascript::ast::EsVersion;
use swc_ecmascript::parser::parse_file_as_module; use swc_ecmascript::parser::parse_file_as_module;
use swc_ecmascript::transforms::pass::noop; use swc_ecmascript::transforms::pass::noop;
...@@ -46,6 +47,7 @@ use swc_ecmascript::visit::Fold; ...@@ -46,6 +47,7 @@ use swc_ecmascript::visit::Fold;
pub mod amp_attributes; pub mod amp_attributes;
mod auto_cjs; mod auto_cjs;
pub mod disallow_re_export_all_in_page; pub mod disallow_re_export_all_in_page;
pub mod emotion;
pub mod hook_optimizer; pub mod hook_optimizer;
pub mod next_dynamic; pub mod next_dynamic;
pub mod next_ssg; pub mod next_ssg;
...@@ -97,13 +99,17 @@ pub struct TransformOptions { ...@@ -97,13 +99,17 @@ pub struct TransformOptions {
#[serde(default)] #[serde(default)]
pub shake_exports: Option<shake_exports::Config>, pub shake_exports: Option<shake_exports::Config>,
#[serde(default)]
pub emotion: Option<emotion::EmotionOptions>,
} }
pub fn custom_before_pass( pub fn custom_before_pass<'a, C: Comments + 'a>(
cm: Arc<SourceMap>, cm: Arc<SourceMap>,
file: Arc<SourceFile>, file: Arc<SourceFile>,
opts: &TransformOptions, opts: &'a TransformOptions,
) -> impl Fold + '_ { comments: C,
) -> impl Fold + 'a {
#[cfg(target_arch = "wasm32")] #[cfg(target_arch = "wasm32")]
let relay_plugin = noop(); let relay_plugin = noop();
...@@ -122,7 +128,7 @@ pub fn custom_before_pass( ...@@ -122,7 +128,7 @@ pub fn custom_before_pass(
chain!( chain!(
disallow_re_export_all_in_page::disallow_re_export_all_in_page(opts.is_page_file), disallow_re_export_all_in_page::disallow_re_export_all_in_page(opts.is_page_file),
styled_jsx::styled_jsx(cm, file.name.clone()), styled_jsx::styled_jsx(cm.clone(), file.name.clone()),
hook_optimizer::hook_optimizer(), hook_optimizer::hook_optimizer(),
match &opts.styled_components { match &opts.styled_components {
Some(config) => { Some(config) => {
...@@ -164,7 +170,27 @@ pub fn custom_before_pass( ...@@ -164,7 +170,27 @@ pub fn custom_before_pass(
match &opts.shake_exports { match &opts.shake_exports {
Some(config) => Either::Left(shake_exports::shake_exports(config.clone())), Some(config) => Either::Left(shake_exports::shake_exports(config.clone())),
None => Either::Right(noop()), None => Either::Right(noop()),
},
opts.emotion
.as_ref()
.and_then(|config| {
if !config.enabled.unwrap_or(false) {
return None;
}
if let FileName::Real(path) = &file.name {
path.to_str().map(|_| {
Either::Left(emotion::EmotionTransformer::new(
config.clone(),
path,
cm,
comments,
))
})
} else {
None
} }
})
.unwrap_or_else(|| Either::Right(noop())),
) )
} }
......
...@@ -44,6 +44,7 @@ struct State { ...@@ -44,6 +44,7 @@ struct State {
} }
impl State { impl State {
#[allow(clippy::wrong_self_convention)]
fn is_data_identifier(&mut self, i: &Ident) -> Result<bool, Error> { fn is_data_identifier(&mut self, i: &Ident) -> Result<bool, Error> {
let ssg_exports = &["getStaticProps", "getStaticPaths", "getServerSideProps"]; let ssg_exports = &["getStaticProps", "getStaticPaths", "getServerSideProps"];
......
...@@ -72,7 +72,7 @@ pub fn transform_css( ...@@ -72,7 +72,7 @@ pub fn transform_css(
let mut s = String::new(); let mut s = String::new();
{ {
let mut wr = BasicCssWriter::new(&mut s, BasicCssWriterConfig { indent: " " }); let mut wr = BasicCssWriter::new(&mut s, None, BasicCssWriterConfig::default());
let mut gen = CodeGenerator::new(&mut wr, CodegenConfig { minify: true }); let mut gen = CodeGenerator::new(&mut wr, CodegenConfig { minify: true });
gen.emit(&ss).unwrap(); gen.emit(&ss).unwrap();
...@@ -144,7 +144,7 @@ impl VisitMut for Namespacer { ...@@ -144,7 +144,7 @@ impl VisitMut for Namespacer {
let mut code = String::new(); let mut code = String::new();
{ {
let mut wr = BasicCssWriter::new(&mut code, BasicCssWriterConfig { indent: " " }); let mut wr = BasicCssWriter::new(&mut code, None, BasicCssWriterConfig::default());
let mut gen = CodeGenerator::new(&mut wr, CodegenConfig { minify: true }); let mut gen = CodeGenerator::new(&mut wr, CodegenConfig { minify: true });
gen.emit(&*node).unwrap(); gen.emit(&*node).unwrap();
...@@ -500,7 +500,7 @@ where ...@@ -500,7 +500,7 @@ where
{ {
let mut s = String::new(); let mut s = String::new();
{ {
let mut wr = BasicCssWriter::new(&mut s, BasicCssWriterConfig { indent: " " }); let mut wr = BasicCssWriter::new(&mut s, None, BasicCssWriterConfig::default());
let mut gen = CodeGenerator::new(&mut wr, CodegenConfig { minify: true }); let mut gen = CodeGenerator::new(&mut wr, CodegenConfig { minify: true });
gen.emit(node).unwrap(); gen.emit(node).unwrap();
......
use next_swc::{ use next_swc::{
amp_attributes::amp_attributes, amp_attributes::amp_attributes,
emotion::{self, EmotionOptions},
next_dynamic::next_dynamic, next_dynamic::next_dynamic,
next_ssg::next_ssg, next_ssg::next_ssg,
page_config::page_config_test, page_config::page_config_test,
...@@ -13,8 +14,11 @@ use std::path::PathBuf; ...@@ -13,8 +14,11 @@ use std::path::PathBuf;
use swc_common::{chain, comments::SingleThreadedComments, FileName, Mark, Span, DUMMY_SP}; use swc_common::{chain, comments::SingleThreadedComments, FileName, Mark, Span, DUMMY_SP};
use swc_ecma_transforms_testing::{test, test_fixture}; use swc_ecma_transforms_testing::{test, test_fixture};
use swc_ecmascript::{ use swc_ecmascript::{
parser::{EsConfig, Syntax}, parser::{EsConfig, Syntax, TsConfig},
transforms::{react::jsx, resolver}, transforms::{
react::{jsx, Runtime},
resolver,
},
}; };
use testing::fixture; use testing::fixture;
...@@ -25,6 +29,13 @@ fn syntax() -> Syntax { ...@@ -25,6 +29,13 @@ fn syntax() -> Syntax {
}) })
} }
fn ts_syntax() -> Syntax {
Syntax::Typescript(TsConfig {
tsx: true,
..Default::default()
})
}
#[fixture("tests/fixture/amp/**/input.js")] #[fixture("tests/fixture/amp/**/input.js")]
fn amp_attributes_fixture(input: PathBuf) { fn amp_attributes_fixture(input: PathBuf) {
let output = input.parent().unwrap().join("output.js"); let output = input.parent().unwrap().join("output.js");
...@@ -260,3 +271,44 @@ fn shake_exports_fixture_default(input: PathBuf) { ...@@ -260,3 +271,44 @@ fn shake_exports_fixture_default(input: PathBuf) {
&output, &output,
); );
} }
#[fixture("tests/fixture/emotion/*/input.tsx")]
fn next_emotion_fixture(input: PathBuf) {
let output = input.parent().unwrap().join("output.ts");
test_fixture(
ts_syntax(),
&|tr| {
let top_level_mark = Mark::fresh(Mark::root());
let jsx = jsx::<SingleThreadedComments>(
tr.cm.clone(),
Some(tr.comments.as_ref().clone()),
swc_ecmascript::transforms::react::Options {
next: false,
runtime: Some(Runtime::Automatic),
throw_if_namespace: false,
development: false,
use_builtins: true,
use_spread: true,
..Default::default()
},
top_level_mark,
);
chain!(
emotion::emotion(
EmotionOptions {
enabled: Some(true),
sourcemap: Some(true),
auto_label: Some(true),
..Default::default()
},
&PathBuf::from("input.ts"),
tr.cm.clone(),
tr.comments.as_ref().clone(),
),
jsx
)
},
&input,
&output,
);
}
import { css, Global } from '@emotion/react'
import styled from '@emotion/styled'
import { PureComponent } from 'react'
import ReactDOM from 'react-dom'
const stylesInCallback = (props: any) =>
css({
color: 'red',
background: 'yellow',
width: `${props.scale * 100}px`,
})
const styles = css({
color: 'red',
width: '20px',
})
const styles2 = css`
color: red;
width: 20px;
`
const DivContainer = styled.div({
background: 'red',
})
const DivContainer2 = styled.div`
background: red;
`
const SpanContainer = styled('span')({
background: 'yellow',
})
const Container = styled('button')`
background: red;
${stylesInCallback}
${() =>
css({
background: 'red',
})}
color: yellow;
font-size: 12px;
`
const Container2 = styled.div`
background: red;
`
export class SimpleComponent extends PureComponent {
render() {
return (
<Container
css={css`
color: hotpink;
`}
>
<Global
styles={css`
html,
body {
padding: 3rem 1rem;
margin: 0;
background: papayawhip;
min-height: 100%;
font-family: Helvetica, Arial, sans-serif;
font-size: 24px;
}
`}
/>
<span>hello</span>
</Container>
)
}
}
ReactDOM.render(<SimpleComponent />, document.querySelector('#app'))
import * as emotionReact from '@emotion/react'
import { PureComponent } from 'react'
import ReactDOM from 'react-dom'
const stylesInCallback = (props: any) =>
emotionReact.css({
color: 'red',
background: 'yellow',
width: `${props.scale * 100}px`,
})
const styles = emotionReact.css({
color: 'red',
width: '20px',
})
const styles2 = emotionReact.css`
color: red;
width: 20px;
`
export class SimpleComponent extends PureComponent {
render() {
return (
<div className={styles}>
<span>hello</span>
</div>
)
}
}
ReactDOM.render(<SimpleComponent />, document.querySelector('#app'))
import { jsx as _jsx } from "react/jsx-runtime";
import * as emotionReact from "@emotion/react";
import { PureComponent } from "react";
import ReactDOM from "react-dom";
const stylesInCallback = (props: any)=>/*#__PURE__*/ emotionReact.css({
color: "red",
background: "yellow",
width: `${props.scale * 100}px`
}, "label:stylesInCallback", "/*# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5wdXQudHMiLCJzb3VyY2VzIjpbImlucHV0LnRzIl0sInNvdXJjZXNDb250ZW50IjpbImltcG9ydCAqIGFzIGVtb3Rpb25SZWFjdCBmcm9tICdAZW1vdGlvbi9yZWFjdCdcbmltcG9ydCB7IFB1cmVDb21wb25lbnQgfSBmcm9tICdyZWFjdCdcbmltcG9ydCBSZWFjdERPTSBmcm9tICdyZWFjdC1kb20nXG5cbmNvbnN0IHN0eWxlc0luQ2FsbGJhY2sgPSAocHJvcHM6IGFueSkgPT5cbiAgZW1vdGlvblJlYWN0LmNzcyh7XG4gICAgY29sb3I6ICdyZWQnLFxuICAgIGJhY2tncm91bmQ6ICd5ZWxsb3cnLFxuICAgIHdpZHRoOiBgJHtwcm9wcy5zY2FsZSAqIDEwMH1weGAsXG4gIH0pXG5cbmNvbnN0IHN0eWxlcyA9IGVtb3Rpb25SZWFjdC5jc3Moe1xuICBjb2xvcjogJ3JlZCcsXG4gIHdpZHRoOiAnMjBweCcsXG59KVxuXG5jb25zdCBzdHlsZXMyID0gZW1vdGlvblJlYWN0LmNzc2BcbiAgY29sb3I6IHJlZDtcbiAgd2lkdGg6IDIwcHg7XG5gXG5cbmV4cG9ydCBjbGFzcyBTaW1wbGVDb21wb25lbnQgZXh0ZW5kcyBQdXJlQ29tcG9uZW50IHtcbiAgcmVuZGVyKCkge1xuICAgIHJldHVybiAoXG4gICAgICA8ZGl2IGNsYXNzTmFtZT17c3R5bGVzfT5cbiAgICAgICAgPHNwYW4+aGVsbG88L3NwYW4+XG4gICAgICA8L2Rpdj5cbiAgICApXG4gIH1cbn1cblxuUmVhY3RET00ucmVuZGVyKDxTaW1wbGVDb21wb25lbnQgLz4sIGRvY3VtZW50LnF1ZXJ5U2VsZWN0b3IoJyNhcHAnKSlcbiJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFLRSJ9 */")
;
const styles = /*#__PURE__*/ emotionReact.css({
color: "red",
width: "20px"
}, "label:styles", "/*# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5wdXQudHMiLCJzb3VyY2VzIjpbImlucHV0LnRzIl0sInNvdXJjZXNDb250ZW50IjpbImltcG9ydCAqIGFzIGVtb3Rpb25SZWFjdCBmcm9tICdAZW1vdGlvbi9yZWFjdCdcbmltcG9ydCB7IFB1cmVDb21wb25lbnQgfSBmcm9tICdyZWFjdCdcbmltcG9ydCBSZWFjdERPTSBmcm9tICdyZWFjdC1kb20nXG5cbmNvbnN0IHN0eWxlc0luQ2FsbGJhY2sgPSAocHJvcHM6IGFueSkgPT5cbiAgZW1vdGlvblJlYWN0LmNzcyh7XG4gICAgY29sb3I6ICdyZWQnLFxuICAgIGJhY2tncm91bmQ6ICd5ZWxsb3cnLFxuICAgIHdpZHRoOiBgJHtwcm9wcy5zY2FsZSAqIDEwMH1weGAsXG4gIH0pXG5cbmNvbnN0IHN0eWxlcyA9IGVtb3Rpb25SZWFjdC5jc3Moe1xuICBjb2xvcjogJ3JlZCcsXG4gIHdpZHRoOiAnMjBweCcsXG59KVxuXG5jb25zdCBzdHlsZXMyID0gZW1vdGlvblJlYWN0LmNzc2BcbiAgY29sb3I6IHJlZDtcbiAgd2lkdGg6IDIwcHg7XG5gXG5cbmV4cG9ydCBjbGFzcyBTaW1wbGVDb21wb25lbnQgZXh0ZW5kcyBQdXJlQ29tcG9uZW50IHtcbiAgcmVuZGVyKCkge1xuICAgIHJldHVybiAoXG4gICAgICA8ZGl2IGNsYXNzTmFtZT17c3R5bGVzfT5cbiAgICAgICAgPHNwYW4+aGVsbG88L3NwYW4+XG4gICAgICA8L2Rpdj5cbiAgICApXG4gIH1cbn1cblxuUmVhY3RET00ucmVuZGVyKDxTaW1wbGVDb21wb25lbnQgLz4sIGRvY3VtZW50LnF1ZXJ5U2VsZWN0b3IoJyNhcHAnKSlcbiJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFXZSJ9 */");
const styles2 = /*#__PURE__*/ emotionReact.css("color:red;width:20px;", "label:styles2", "/*# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5wdXQudHMiLCJzb3VyY2VzIjpbImlucHV0LnRzIl0sInNvdXJjZXNDb250ZW50IjpbImltcG9ydCAqIGFzIGVtb3Rpb25SZWFjdCBmcm9tICdAZW1vdGlvbi9yZWFjdCdcbmltcG9ydCB7IFB1cmVDb21wb25lbnQgfSBmcm9tICdyZWFjdCdcbmltcG9ydCBSZWFjdERPTSBmcm9tICdyZWFjdC1kb20nXG5cbmNvbnN0IHN0eWxlc0luQ2FsbGJhY2sgPSAocHJvcHM6IGFueSkgPT5cbiAgZW1vdGlvblJlYWN0LmNzcyh7XG4gICAgY29sb3I6ICdyZWQnLFxuICAgIGJhY2tncm91bmQ6ICd5ZWxsb3cnLFxuICAgIHdpZHRoOiBgJHtwcm9wcy5zY2FsZSAqIDEwMH1weGAsXG4gIH0pXG5cbmNvbnN0IHN0eWxlcyA9IGVtb3Rpb25SZWFjdC5jc3Moe1xuICBjb2xvcjogJ3JlZCcsXG4gIHdpZHRoOiAnMjBweCcsXG59KVxuXG5jb25zdCBzdHlsZXMyID0gZW1vdGlvblJlYWN0LmNzc2BcbiAgY29sb3I6IHJlZDtcbiAgd2lkdGg6IDIwcHg7XG5gXG5cbmV4cG9ydCBjbGFzcyBTaW1wbGVDb21wb25lbnQgZXh0ZW5kcyBQdXJlQ29tcG9uZW50IHtcbiAgcmVuZGVyKCkge1xuICAgIHJldHVybiAoXG4gICAgICA8ZGl2IGNsYXNzTmFtZT17c3R5bGVzfT5cbiAgICAgICAgPHNwYW4+aGVsbG88L3NwYW4+XG4gICAgICA8L2Rpdj5cbiAgICApXG4gIH1cbn1cblxuUmVhY3RET00ucmVuZGVyKDxTaW1wbGVDb21wb25lbnQgLz4sIGRvY3VtZW50LnF1ZXJ5U2VsZWN0b3IoJyNhcHAnKSlcbiJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFnQmdCIn0= */");
export class SimpleComponent extends PureComponent {
render() {
return /*#__PURE__*/ _jsx("div", {
className: styles,
children: /*#__PURE__*/ _jsx("span", {
children: "hello"
})
});
}
}
ReactDOM.render(/*#__PURE__*/ _jsx(SimpleComponent, {}), document.querySelector("#app"));
...@@ -3,7 +3,7 @@ export default (()=><div className={"jsx-713499aa363d6373"}> ...@@ -3,7 +3,7 @@ export default (()=><div className={"jsx-713499aa363d6373"}>
<p className={"jsx-713499aa363d6373"}>test</p> <p className={"jsx-713499aa363d6373"}>test</p>
<_JSXStyle id={"713499aa363d6373"}>{"p.jsx-713499aa363d6373 a.jsx-713499aa363d6373 span.jsx-713499aa363d6373{color:red}p.jsx-713499aa363d6373 span{background:blue}p.jsx-713499aa363d6373 a[title=\"'w ' ' t'\"].jsx-713499aa363d6373{margin:auto}p.jsx-713499aa363d6373 span:not(.test){color:green}p.jsx-713499aa363d6373,h1.jsx-713499aa363d6373{color:blue;-webkit-animation:hahaha 3s ease forwards infinite;-moz-animation:hahaha 3s ease forwards infinite;-o-animation:hahaha 3s ease forwards infinite;animation:hahaha 3s ease forwards infinite;-webkit-animation-name:hahaha;-moz-animation-name:hahaha;-o-animation-name:hahaha;animation-name:hahaha;-webkit-animation-delay:100ms;-moz-animation-delay:100ms;-o-animation-delay:100ms;animation-delay:100ms}p.jsx-713499aa363d6373{-webkit-animation:hahaha 1s,hehehe 2s;-moz-animation:hahaha 1s,hehehe 2s;-o-animation:hahaha 1s,hehehe 2s;animation:hahaha 1s,hehehe 2s}p.jsx-713499aa363d6373:hover{color:red}p.jsx-713499aa363d6373::before{color:red}.jsx-713499aa363d6373:hover{color:red}.jsx-713499aa363d6373::before{color:red}.jsx-713499aa363d6373:hover p.jsx-713499aa363d6373{color:red}p.jsx-713499aa363d6373+a.jsx-713499aa363d6373{color:red}p.jsx-713499aa363d6373~a.jsx-713499aa363d6373{color:red}p.jsx-713499aa363d6373>a.jsx-713499aa363d6373{color:red}@keyframes hahaha{from{top:0}to{top:100}}@keyframes hehehe{from{left:0}to{left:100}}@media(min-width:500px){.test.jsx-713499aa363d6373{color:red}}.test.jsx-713499aa363d6373{display:block}.inline-flex.jsx-713499aa363d6373{display:-webkit-inline-box;display:-webkit-inline-flex;display:-moz-inline-box;display:-ms-inline-flexbox;display:inline-flex}.flex.jsx-713499aa363d6373{display:-webkit-box;display:-webkit-flex;display:-moz-box;display:-ms-flexbox;display:flex}.test.jsx-713499aa363d6373{box-shadow:0 0 10px black,inset 0 0 5px black}.test[title=\",\"].jsx-713499aa363d6373{display:inline-block}.test.is-status.jsx-713499aa363d6373 .test.jsx-713499aa363d6373{color:red}.a-selector.jsx-713499aa363d6373:hover,.a-selector.jsx-713499aa363d6373:focus{outline:none}"}</_JSXStyle> <_JSXStyle id={"713499aa363d6373"}>{"p.jsx-713499aa363d6373 a.jsx-713499aa363d6373 span.jsx-713499aa363d6373{color:red}p.jsx-713499aa363d6373 span{background:blue}p.jsx-713499aa363d6373 a[title=\"'w ' ' t'\"].jsx-713499aa363d6373{margin:auto}p.jsx-713499aa363d6373 span:not(.test){color:green}p.jsx-713499aa363d6373,h1.jsx-713499aa363d6373{color:blue;-webkit-animation:hahaha 3s ease forwards infinite;-moz-animation:hahaha 3s ease forwards infinite;-o-animation:hahaha 3s ease forwards infinite;animation:hahaha 3s ease forwards infinite;-webkit-animation-name:hahaha;-moz-animation-name:hahaha;-o-animation-name:hahaha;animation-name:hahaha;-webkit-animation-delay:100ms;-moz-animation-delay:100ms;-o-animation-delay:100ms;animation-delay:100ms}p.jsx-713499aa363d6373{-webkit-animation:hahaha 1s,hehehe 2s;-moz-animation:hahaha 1s,hehehe 2s;-o-animation:hahaha 1s,hehehe 2s;animation:hahaha 1s,hehehe 2s}p.jsx-713499aa363d6373:hover{color:red}p.jsx-713499aa363d6373::before{color:red}.jsx-713499aa363d6373:hover{color:red}.jsx-713499aa363d6373::before{color:red}.jsx-713499aa363d6373:hover p.jsx-713499aa363d6373{color:red}p.jsx-713499aa363d6373+a.jsx-713499aa363d6373{color:red}p.jsx-713499aa363d6373~a.jsx-713499aa363d6373{color:red}p.jsx-713499aa363d6373>a.jsx-713499aa363d6373{color:red}@keyframes hahaha{from{top:0}to{top:100}}@keyframes hehehe{from{left:0}to{left:100}}@media(min-width:500px){.test.jsx-713499aa363d6373{color:red}}.test.jsx-713499aa363d6373{display:block}.inline-flex.jsx-713499aa363d6373{display:-webkit-inline-box;display:-webkit-inline-flex;display:-moz-inline-box;display:-ms-inline-flexbox;display:inline-flex}.flex.jsx-713499aa363d6373{display:-webkit-box;display:-webkit-flex;display:-moz-box;display:-ms-flexbox;display:flex}.test.jsx-713499aa363d6373{-webkit-box-shadow:0 0 10px black,inset 0 0 5px black;-moz-box-shadow:0 0 10px black,inset 0 0 5px black;box-shadow:0 0 10px black,inset 0 0 5px black}.test[title=\",\"].jsx-713499aa363d6373{display:inline-block}.test.is-status.jsx-713499aa363d6373 .test.jsx-713499aa363d6373{color:red}.a-selector.jsx-713499aa363d6373:hover,.a-selector.jsx-713499aa363d6373:focus{outline:none}"}</_JSXStyle>
</div> </div>
); );
...@@ -3,7 +3,7 @@ export default (()=><div className={"jsx-768337a97aceabd1"}> ...@@ -3,7 +3,7 @@ export default (()=><div className={"jsx-768337a97aceabd1"}>
<p className={"jsx-768337a97aceabd1"}>test</p> <p className={"jsx-768337a97aceabd1"}>test</p>
<_JSXStyle id={"768337a97aceabd1"}>{"html.jsx-768337a97aceabd1{background-image:linear-gradient(0deg,rgba(255,255,255,.8),rgba(255,255,255,.8)),url(/static/background.svg)}p{color:blue}p{color:blue}p,a.jsx-768337a97aceabd1{color:blue}.foo+a{color:red}body{font-family:-apple-system,BlinkMacSystemFont,\"Segoe UI\",Helvetica,Arial,sans-serif}p.jsx-768337a97aceabd1{color:red}p.jsx-768337a97aceabd1{color:red}*.jsx-768337a97aceabd1{color:blue}[href=\"woot\"].jsx-768337a97aceabd1{color:red}p.jsx-768337a97aceabd1 a.jsx-768337a97aceabd1 span.jsx-768337a97aceabd1{color:red}p.jsx-768337a97aceabd1 span{background:blue}p.jsx-768337a97aceabd1 a[title=\"'w ' ' t'\"].jsx-768337a97aceabd1{margin:auto}p.jsx-768337a97aceabd1 span:not(.test){color:green}p.jsx-768337a97aceabd1,h1.jsx-768337a97aceabd1{color:blue;-webkit-animation:hahaha 3s ease forwards infinite;-moz-animation:hahaha 3s ease forwards infinite;-o-animation:hahaha 3s ease forwards infinite;animation:hahaha 3s ease forwards infinite;-webkit-animation-name:hahaha;-moz-animation-name:hahaha;-o-animation-name:hahaha;animation-name:hahaha;-webkit-animation-delay:100ms;-moz-animation-delay:100ms;-o-animation-delay:100ms;animation-delay:100ms}p.jsx-768337a97aceabd1{-webkit-animation:hahaha 1s,hehehe 2s;-moz-animation:hahaha 1s,hehehe 2s;-o-animation:hahaha 1s,hehehe 2s;animation:hahaha 1s,hehehe 2s}p.jsx-768337a97aceabd1:hover{color:red}p.jsx-768337a97aceabd1::before{color:red}.jsx-768337a97aceabd1:hover{color:red}.jsx-768337a97aceabd1::before{color:red}.jsx-768337a97aceabd1:hover p.jsx-768337a97aceabd1{color:red}p.jsx-768337a97aceabd1+a.jsx-768337a97aceabd1{color:red}p.jsx-768337a97aceabd1~a.jsx-768337a97aceabd1{color:red}p.jsx-768337a97aceabd1>a.jsx-768337a97aceabd1{color:red}@keyframes hahaha{from{top:0}to{top:100}}@keyframes hehehe{from{left:0}to{left:100}}@media(min-width:500px){.test.jsx-768337a97aceabd1{color:red}}.test.jsx-768337a97aceabd1{display:block}.inline-flex.jsx-768337a97aceabd1{display:-webkit-inline-box;display:-webkit-inline-flex;display:-moz-inline-box;display:-ms-inline-flexbox;display:inline-flex}.flex.jsx-768337a97aceabd1{display:-webkit-box;display:-webkit-flex;display:-moz-box;display:-ms-flexbox;display:flex}.test.jsx-768337a97aceabd1{box-shadow:0 0 10px black,inset 0 0 5px black}.test[title=\",\"].jsx-768337a97aceabd1{display:inline-block}.test.is-status.jsx-768337a97aceabd1 .test.jsx-768337a97aceabd1{color:red}.a-selector.jsx-768337a97aceabd1:hover,.a-selector.jsx-768337a97aceabd1:focus{outline:none}@media(min-width:1px)and (max-width:768px){[class*=\"grid__col--\"].jsx-768337a97aceabd1{margin-top:12px;margin-bottom:12px}}@media(max-width:64em){.test.jsx-768337a97aceabd1{margin-bottom:1em}@supports(-moz-appearance:none)and (display:contents){.test.jsx-768337a97aceabd1{margin-bottom:2rem}}}"}</_JSXStyle> <_JSXStyle id={"768337a97aceabd1"}>{"html.jsx-768337a97aceabd1{background-image:linear-gradient(0deg,rgba(255,255,255,.8),rgba(255,255,255,.8)),url(/static/background.svg)}p{color:blue}p{color:blue}p,a.jsx-768337a97aceabd1{color:blue}.foo+a{color:red}body{font-family:-apple-system,BlinkMacSystemFont,\"Segoe UI\",Helvetica,Arial,sans-serif}p.jsx-768337a97aceabd1{color:red}p.jsx-768337a97aceabd1{color:red}*.jsx-768337a97aceabd1{color:blue}[href=\"woot\"].jsx-768337a97aceabd1{color:red}p.jsx-768337a97aceabd1 a.jsx-768337a97aceabd1 span.jsx-768337a97aceabd1{color:red}p.jsx-768337a97aceabd1 span{background:blue}p.jsx-768337a97aceabd1 a[title=\"'w ' ' t'\"].jsx-768337a97aceabd1{margin:auto}p.jsx-768337a97aceabd1 span:not(.test){color:green}p.jsx-768337a97aceabd1,h1.jsx-768337a97aceabd1{color:blue;-webkit-animation:hahaha 3s ease forwards infinite;-moz-animation:hahaha 3s ease forwards infinite;-o-animation:hahaha 3s ease forwards infinite;animation:hahaha 3s ease forwards infinite;-webkit-animation-name:hahaha;-moz-animation-name:hahaha;-o-animation-name:hahaha;animation-name:hahaha;-webkit-animation-delay:100ms;-moz-animation-delay:100ms;-o-animation-delay:100ms;animation-delay:100ms}p.jsx-768337a97aceabd1{-webkit-animation:hahaha 1s,hehehe 2s;-moz-animation:hahaha 1s,hehehe 2s;-o-animation:hahaha 1s,hehehe 2s;animation:hahaha 1s,hehehe 2s}p.jsx-768337a97aceabd1:hover{color:red}p.jsx-768337a97aceabd1::before{color:red}.jsx-768337a97aceabd1:hover{color:red}.jsx-768337a97aceabd1::before{color:red}.jsx-768337a97aceabd1:hover p.jsx-768337a97aceabd1{color:red}p.jsx-768337a97aceabd1+a.jsx-768337a97aceabd1{color:red}p.jsx-768337a97aceabd1~a.jsx-768337a97aceabd1{color:red}p.jsx-768337a97aceabd1>a.jsx-768337a97aceabd1{color:red}@keyframes hahaha{from{top:0}to{top:100}}@keyframes hehehe{from{left:0}to{left:100}}@media(min-width:500px){.test.jsx-768337a97aceabd1{color:red}}.test.jsx-768337a97aceabd1{display:block}.inline-flex.jsx-768337a97aceabd1{display:-webkit-inline-box;display:-webkit-inline-flex;display:-moz-inline-box;display:-ms-inline-flexbox;display:inline-flex}.flex.jsx-768337a97aceabd1{display:-webkit-box;display:-webkit-flex;display:-moz-box;display:-ms-flexbox;display:flex}.test.jsx-768337a97aceabd1{-webkit-box-shadow:0 0 10px black,inset 0 0 5px black;-moz-box-shadow:0 0 10px black,inset 0 0 5px black;box-shadow:0 0 10px black,inset 0 0 5px black}.test[title=\",\"].jsx-768337a97aceabd1{display:inline-block}.test.is-status.jsx-768337a97aceabd1 .test.jsx-768337a97aceabd1{color:red}.a-selector.jsx-768337a97aceabd1:hover,.a-selector.jsx-768337a97aceabd1:focus{outline:none}@media(min-width:1px)and (max-width:768px){[class*=\"grid__col--\"].jsx-768337a97aceabd1{margin-top:12px;margin-bottom:12px}}@media(max-width:64em){.test.jsx-768337a97aceabd1{margin-bottom:1em}@supports(-moz-appearance:none)and (display:contents){.test.jsx-768337a97aceabd1{margin-bottom:2rem}}}"}</_JSXStyle>
</div> </div>
); );
...@@ -61,6 +61,7 @@ fn test(input: &Path, minify: bool) { ...@@ -61,6 +61,7 @@ fn test(input: &Path, minify: bool) {
react_remove_properties: None, react_remove_properties: None,
relay: None, relay: None,
shake_exports: None, shake_exports: None,
emotion: Some(assert_json("{}")),
}; };
let options = options.patch(&fm); let options = options.patch(&fm);
...@@ -70,8 +71,10 @@ fn test(input: &Path, minify: bool) { ...@@ -70,8 +71,10 @@ fn test(input: &Path, minify: bool) {
None, None,
&handler, &handler,
&options.swc, &options.swc,
|_| custom_before_pass(cm.clone(), fm.clone(), &options), |_, comments| {
|_| noop(), custom_before_pass(cm.clone(), fm.clone(), &options, comments.clone())
},
|_, _| noop(),
) { ) {
Ok(v) => { Ok(v) => {
NormalizedOutput::from(v.code) NormalizedOutput::from(v.code)
......
...@@ -5,9 +5,9 @@ function b(c, a) { ...@@ -5,9 +5,9 @@ function b(c, a) {
} }
import a from "other"; import a from "other";
(function(c, b) { (function(c, b) {
return (function(c) { return function(c) {
if (Array.isArray(c)) return c; if (Array.isArray(c)) return c;
})(c) || (function(c, b) { }(c) || function(c, b) {
var g, h, a = null == c ? null : "undefined" != typeof Symbol && c[Symbol.iterator] || c["@@iterator"]; var g, h, a = null == c ? null : "undefined" != typeof Symbol && c[Symbol.iterator] || c["@@iterator"];
if (null != a) { if (null != a) {
var d = [], e = !0, i = !1; var d = [], e = !0, i = !1;
...@@ -24,16 +24,16 @@ import a from "other"; ...@@ -24,16 +24,16 @@ import a from "other";
} }
return d; return d;
} }
})(c, b) || (function(a, d) { }(c, b) || function(a, d) {
if (a) { if (a) {
if ("string" == typeof a) return b(a, d); if ("string" == typeof a) return b(a, d);
var c = Object.prototype.toString.call(a).slice(8, -1); var c = Object.prototype.toString.call(a).slice(8, -1);
if ("Object" === c && a.constructor && (c = a.constructor.name), "Map" === c || "Set" === c) return Array.from(c); if ("Object" === c && a.constructor && (c = a.constructor.name), "Map" === c || "Set" === c) return Array.from(c);
if ("Arguments" === c || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(c)) return b(a, d); if ("Arguments" === c || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(c)) return b(a, d);
} }
})(c, b) || (function() { }(c, b) || function() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
})(); }();
})(a, 1)[0]; })(a, 1)[0];
var c = function() { var c = function() {
"use strict"; "use strict";
......
...@@ -57,5 +57,5 @@ var Foo = function Foo() { ...@@ -57,5 +57,5 @@ var Foo = function Foo() {
}; };
export var __N_SSG = true; export var __N_SSG = true;
export default function Home() { export default function Home() {
return(/*#__PURE__*/ React.createElement("div", null)); return /*#__PURE__*/ React.createElement("div", null);
}; };
import _JSXStyle from "styled-jsx/style"; 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) {
return(/*#__PURE__*/ React.createElement("form", { return /*#__PURE__*/ React.createElement("form", {
className: "jsx-eb368961fd3b0a99" className: "jsx-eb368961fd3b0a99"
})); });
}, },
className: "jsx-eb368961fd3b0a99" className: "jsx-eb368961fd3b0a99"
}, React.createElement(_JSXStyle, { }, React.createElement(_JSXStyle, {
id: "eb368961fd3b0a99" id: "eb368961fd3b0a99"
}, "span.jsx-eb368961fd3b0a99{color:red}"))); }, "span.jsx-eb368961fd3b0a99{color:red}"));
}; };
...@@ -9,11 +9,11 @@ export default function Home() { ...@@ -9,11 +9,11 @@ export default function Home() {
useEffect(function() { useEffect(function() {
new MyClass(); new MyClass();
}, []); }, []);
return(/*#__PURE__*/ React.createElement("svg", null, /*#__PURE__*/ React.createElement("g", { return /*#__PURE__*/ React.createElement("svg", null, /*#__PURE__*/ React.createElement("g", {
className: "group" className: "group"
}, /*#__PURE__*/ React.createElement("path", null), /*#__PURE__*/ React.createElement("path", null)), /*#__PURE__*/ React.createElement("g", { }, /*#__PURE__*/ React.createElement("path", null), /*#__PURE__*/ React.createElement("path", null)), /*#__PURE__*/ React.createElement("g", {
className: "group" className: "group"
}, /*#__PURE__*/ React.createElement("path", null), /*#__PURE__*/ React.createElement("path", null)))); }, /*#__PURE__*/ React.createElement("path", null), /*#__PURE__*/ React.createElement("path", null)));
}; };
var MyClass = function MyClass() { var MyClass = function MyClass() {
"use strict"; "use strict";
......
...@@ -12,16 +12,16 @@ backtrace = "0.3" ...@@ -12,16 +12,16 @@ backtrace = "0.3"
fxhash = "0.2.1" fxhash = "0.2.1"
napi = {version = "1", features = ["serde-json"]} napi = {version = "1", features = ["serde-json"]}
napi-derive = "1" napi-derive = "1"
next-swc = {version = "0.0.0", path = "../core"}
once_cell = "1.8.0" once_cell = "1.8.0"
serde = "1" serde = "1"
serde_json = "1" serde_json = "1"
next-swc = { version = "0.0.0", path = "../core" } swc = "0.150.1"
swc = "0.146.0" swc_atoms = "0.2.9"
swc_atoms = "0.2.7" swc_bundler = {version = "0.122.0", features = ["concurrent"]}
swc_bundler = { version = "0.120.0", features = ["concurrent"] } swc_common = {version = "0.17.15", features = ["concurrent", "sourcemap"]}
swc_common = { version = "0.17.11", features = ["concurrent", "sourcemap"] } swc_ecma_loader = {version = "0.29.0", features = ["node", "lru"]}
swc_ecma_loader = { version = "0.29.0", features = ["node", "lru"] } swc_ecmascript = {version = "0.132.0", features = ["codegen", "minifier", "optimization", "parser", "react", "transforms", "typescript", "utils", "visit"]}
swc_ecmascript = { version = "0.130.0", features = ["codegen", "minifier", "optimization", "parser", "react", "transforms", "typescript", "utils", "visit"] }
swc_node_base = "0.5.1" swc_node_base = "0.5.1"
[build-dependencies] [build-dependencies]
......
...@@ -54,8 +54,8 @@ impl Task for BundleTask { ...@@ -54,8 +54,8 @@ impl Task for BundleTask {
try_with_handler(self.c.cm.clone(), true, |handler| { try_with_handler(self.c.cm.clone(), true, |handler| {
let builtins = NODE_BUILTINS let builtins = NODE_BUILTINS
.to_vec() .iter()
.into_iter() .copied()
.map(JsWord::from) .map(JsWord::from)
.collect::<Vec<_>>(); .collect::<Vec<_>>();
......
...@@ -94,14 +94,16 @@ impl Task for TransformTask { ...@@ -94,14 +94,16 @@ impl Task for TransformTask {
}; };
let options = options.patch(&fm); let options = options.patch(&fm);
let before_pass = custom_before_pass(self.c.cm.clone(), fm.clone(), &options); let cm = self.c.cm.clone();
let file = fm.clone();
self.c.process_js_with_custom_pass( self.c.process_js_with_custom_pass(
fm, fm,
None, None,
handler, handler,
&options.swc, &options.swc,
|_| before_pass, |_, comments| custom_before_pass(cm, file, &options, comments.clone()),
|_| noop(), |_, _| noop(),
) )
}) })
}) })
......
...@@ -10,15 +10,15 @@ crate-type = ["cdylib"] ...@@ -10,15 +10,15 @@ crate-type = ["cdylib"]
[dependencies] [dependencies]
anyhow = "1.0.42" anyhow = "1.0.42"
console_error_panic_hook = "0.1.6" console_error_panic_hook = "0.1.6"
next-swc = {version = "0.0.0", path = "../core"}
once_cell = "1.3.1" once_cell = "1.3.1"
parking_lot_core = "=0.8.0" parking_lot_core = "=0.8.0"
path-clean = "0.1" path-clean = "0.1"
serde = {version = "1", features = ["derive"]} serde = {version = "1", features = ["derive"]}
serde_json = "1" serde_json = "1"
next-swc = { version = "0.0.0", path = "../core" } swc = "0.150.1"
swc = "0.146.0" swc_common = {version = "0.17.14", features = ["concurrent", "sourcemap"]}
swc_common = { version = "0.17.11", features = ["concurrent", "sourcemap"] } swc_ecmascript = {version = "0.132.0", features = ["codegen", "minifier", "optimization", "parser", "react", "transforms", "typescript", "utils", "visit"]}
swc_ecmascript = { version = "0.130.0", features = ["codegen", "minifier", "optimization", "parser", "react", "transforms", "typescript", "utils", "visit"] }
tracing = {version = "0.1.28", features = ["release_max_level_off"]} tracing = {version = "0.1.28", features = ["release_max_level_off"]}
wasm-bindgen = {version = "0.2", features = ["serde-serialize"]} wasm-bindgen = {version = "0.2", features = ["serde-serialize"]}
wasm-bindgen-futures = "0.4.8" wasm-bindgen-futures = "0.4.8"
...@@ -47,9 +47,17 @@ pub fn transform_sync(s: &str, opts: JsValue) -> Result<JsValue, JsValue> { ...@@ -47,9 +47,17 @@ pub fn transform_sync(s: &str, opts: JsValue) -> Result<JsValue, JsValue> {
}, },
s.into(), s.into(),
); );
let before_pass = custom_before_pass(c.cm.clone(), fm.clone(), &opts); let cm = c.cm.clone();
let file = fm.clone();
let out = c let out = c
.process_js_with_custom_pass(fm, None, handler, &opts.swc, |_| before_pass, |_| noop()) .process_js_with_custom_pass(
fm,
None,
handler,
&opts.swc,
|_, comments| custom_before_pass(cm, file, &opts, comments.clone()),
|_, _| noop(),
)
.context("failed to process js file")?; .context("failed to process js file")?;
JsValue::from_serde(&out).context("failed to serialize json") JsValue::from_serde(&out).context("failed to serialize json")
......
nightly-2021-11-15 nightly-2022-02-23
\ No newline at end of file \ No newline at end of file
...@@ -64,7 +64,9 @@ function getBaseSWCOptions({ ...@@ -64,7 +64,9 @@ function getBaseSWCOptions({
legacyDecorator: enableDecorators, legacyDecorator: enableDecorators,
decoratorMetadata: emitDecoratorMetadata, decoratorMetadata: emitDecoratorMetadata,
react: { react: {
importSource: jsConfig?.compilerOptions?.jsxImportSource || 'react', importSource: nextConfig?.experimental?.emotion
? '@emotion/react'
: jsConfig?.compilerOptions?.jsxImportSource || 'react',
runtime: 'automatic', runtime: 'automatic',
pragma: 'React.createElement', pragma: 'React.createElement',
pragmaFrag: 'React.Fragment', pragmaFrag: 'React.Fragment',
...@@ -101,6 +103,34 @@ function getBaseSWCOptions({ ...@@ -101,6 +103,34 @@ function getBaseSWCOptions({
removeConsole: nextConfig?.compiler?.removeConsole, removeConsole: nextConfig?.compiler?.removeConsole,
reactRemoveProperties: nextConfig?.compiler?.reactRemoveProperties, reactRemoveProperties: nextConfig?.compiler?.reactRemoveProperties,
relay: nextConfig?.compiler?.relay, relay: nextConfig?.compiler?.relay,
emotion: getEmotionOptions(nextConfig, development),
}
}
function getEmotionOptions(nextConfig, development) {
if (!nextConfig?.experimental?.emotion) {
return null
}
let autoLabel = false
switch (nextConfig?.experimental?.emotion?.autoLabel) {
case 'never':
autoLabel = false
break
case 'always':
autoLabel = true
break
case 'dev-only':
default:
autoLabel = !!development
break
}
return {
enabled: true,
autoLabel,
labelFormat: nextConfig?.experimental?.emotion?.labelFormat,
sourcemap: development
? nextConfig?.experimental?.emotion?.sourceMap ?? true
: false,
} }
} }
......
...@@ -1505,6 +1505,7 @@ export default async function getBaseWebpackConfig( ...@@ -1505,6 +1505,7 @@ export default async function getBaseWebpackConfig(
], ],
['swcRemoveConsole', !!config.compiler?.removeConsole], ['swcRemoveConsole', !!config.compiler?.removeConsole],
['swcImportSource', !!jsConfig?.compilerOptions?.jsxImportSource], ['swcImportSource', !!jsConfig?.compilerOptions?.jsxImportSource],
['swcEmotion', !!config.experimental.emotion],
]) ])
), ),
].filter(Boolean as any as ExcludesFalse), ].filter(Boolean as any as ExcludesFalse),
...@@ -1633,6 +1634,7 @@ export default async function getBaseWebpackConfig( ...@@ -1633,6 +1634,7 @@ export default async function getBaseWebpackConfig(
reactRemoveProperties: config.compiler?.reactRemoveProperties, reactRemoveProperties: config.compiler?.reactRemoveProperties,
styledComponents: config.compiler?.styledComponents, styledComponents: config.compiler?.styledComponents,
relay: config.compiler?.relay, relay: config.compiler?.relay,
emotion: config.experimental?.emotion,
}) })
const cache: any = { const cache: any = {
......
...@@ -12,6 +12,7 @@ type Feature = ...@@ -12,6 +12,7 @@ type Feature =
| 'swcExperimentalDecorators' | 'swcExperimentalDecorators'
| 'swcRemoveConsole' | 'swcRemoveConsole'
| 'swcImportSource' | 'swcImportSource'
| 'swcEmotion'
interface FeatureUsage { interface FeatureUsage {
featureName: Feature featureName: Feature
...@@ -50,6 +51,7 @@ const BUILD_FEATURES: Array<Feature> = [ ...@@ -50,6 +51,7 @@ const BUILD_FEATURES: Array<Feature> = [
'swcExperimentalDecorators', 'swcExperimentalDecorators',
'swcRemoveConsole', 'swcRemoveConsole',
'swcImportSource', 'swcImportSource',
'swcEmotion',
] ]
/** /**
......
...@@ -111,6 +111,13 @@ export interface ExperimentalConfig { ...@@ -111,6 +111,13 @@ export interface ExperimentalConfig {
layoutRaw: boolean layoutRaw: boolean
} }
middlewareSourceMaps?: boolean middlewareSourceMaps?: boolean
emotion?:
| boolean
| {
sourceMap?: boolean
autoLabel?: 'dev-only' | 'always' | 'never'
labelFormat?: string
}
} }
/** /**
......
...@@ -143,6 +143,7 @@ export type EventBuildFeatureUsage = { ...@@ -143,6 +143,7 @@ export type EventBuildFeatureUsage = {
| 'swcExperimentalDecorators' | 'swcExperimentalDecorators'
| 'swcRemoveConsole' | 'swcRemoveConsole'
| 'swcImportSource' | 'swcImportSource'
| 'swcEmotion'
| 'build-lint' | 'build-lint'
invocationCount: number invocationCount: number
} }
......
...@@ -15,7 +15,7 @@ error: Unexpected token \`jsx name (Component)\`. Expected this, import, async, ...@@ -15,7 +15,7 @@ error: Unexpected token \`jsx name (Component)\`. Expected this, import, async,
| ^^^^^^^^^ | ^^^^^^^^^
Caused by: Caused by:
0: failed to process js file 0: failed to process input file
1: Syntax Error" 1: Syntax Error"
`; `;
...@@ -28,6 +28,6 @@ Error: error: Unexpected token \`{\`. Expected identifier, string literal, numer ...@@ -28,6 +28,6 @@ Error: error: Unexpected token \`{\`. Expected identifier, string literal, numer
| ^ | ^
Caused by: Caused by:
0: failed to process js file 0: failed to process input file
1: Syntax Error" 1: Syntax Error"
`; `;
...@@ -75,7 +75,7 @@ Error: error: Unexpected eof ...@@ -75,7 +75,7 @@ Error: error: Unexpected eof
| ^ | ^
Caused by: Caused by:
0: failed to process js file 0: failed to process input file
1: Syntax Error" 1: Syntax Error"
`; `;
...@@ -135,7 +135,7 @@ Error: error: Unexpected eof ...@@ -135,7 +135,7 @@ Error: error: Unexpected eof
| ^ | ^
Caused by: Caused by:
0: failed to process js file 0: failed to process input file
1: Syntax Error" 1: Syntax Error"
`; `;
...@@ -148,7 +148,7 @@ Error: error: Unexpected eof ...@@ -148,7 +148,7 @@ Error: error: Unexpected eof
| ^ | ^
Caused by: Caused by:
0: failed to process js file 0: failed to process input file
1: Syntax Error" 1: Syntax Error"
`; `;
...@@ -161,6 +161,6 @@ Error: error: Unexpected eof ...@@ -161,6 +161,6 @@ Error: error: Unexpected eof
| ^ | ^
Caused by: Caused by:
0: failed to process js file 0: failed to process input file
1: Syntax Error" 1: Syntax Error"
`; `;
...@@ -631,6 +631,7 @@ describe('Telemetry CLI', () => { ...@@ -631,6 +631,7 @@ describe('Telemetry CLI', () => {
regex.exec(stderr).pop() // swcReactRemoveProperties regex.exec(stderr).pop() // swcReactRemoveProperties
regex.exec(stderr).pop() // swcRemoveConsole regex.exec(stderr).pop() // swcRemoveConsole
regex.exec(stderr).pop() // swcImportSource regex.exec(stderr).pop() // swcImportSource
regex.exec(stderr).pop() // swcEmotion
const image = regex.exec(stderr).pop() const image = regex.exec(stderr).pop()
expect(image).toContain(`"featureName": "next/image"`) expect(image).toContain(`"featureName": "next/image"`)
expect(image).toContain(`"invocationCount": 1`) expect(image).toContain(`"invocationCount": 1`)
......
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