Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make next-ssg optional #28862

Merged
merged 5 commits into from
Sep 13, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 26 additions & 15 deletions packages/next/build/swc/src/transform.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,10 @@ use crate::{
};
use anyhow::{Context as _, Error};
use napi::{CallContext, Env, JsBoolean, JsObject, JsString, Task};
use serde::Deserialize;
use std::sync::Arc;
use swc::{config::Options, try_with_handler, Compiler, TransformOutput};
use swc_common::{chain, FileName, SourceFile};
use swc::{try_with_handler, Compiler, TransformOutput};
use swc_common::{chain, pass::Optional, FileName, SourceFile};
use swc_ecmascript::ast::Program;
use swc_ecmascript::transforms::pass::noop;

Expand All @@ -49,10 +50,20 @@ pub enum Input {
Source(Arc<SourceFile>),
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct TransformOptions {
#[serde(flatten)]
swc: swc::config::Options,

#[serde(default)]
pub disable_next_ssg: bool,
}

pub struct TransformTask {
pub c: Arc<Compiler>,
pub input: Input,
pub options: Options,
pub options: TransformOptions,
}

impl Task for TransformTask {
Expand All @@ -65,14 +76,14 @@ impl Task for TransformTask {
Input::Source(ref s) => {
let before_pass = chain!(
hook_optimizer(),
next_ssg(),
Optional::new(next_ssg(), !self.options.disable_next_ssg),
amp_attributes(),
next_dynamic(s.name.clone()),
);
self.c.process_js_with_custom_pass(
s.clone(),
&handler,
&self.options,
&self.options.swc,
before_pass,
noop(),
)
Expand All @@ -90,13 +101,13 @@ impl Task for TransformTask {
/// returns `compiler, (src / path), options, plugin, callback`
pub fn schedule_transform<F>(cx: CallContext, op: F) -> napi::Result<JsObject>
where
F: FnOnce(&Arc<Compiler>, String, bool, Options) -> TransformTask,
F: FnOnce(&Arc<Compiler>, String, bool, TransformOptions) -> TransformTask,
{
let c = get_compiler(&cx);

let s = cx.get::<JsString>(0)?.into_utf8()?.as_str()?.to_owned();
let is_module = cx.get::<JsBoolean>(1)?;
let options: Options = cx.get_deserialized(2)?;
let options: TransformOptions = cx.get_deserialized(2)?;

let task = op(&c, s, is_module.get_value()?, options);

Expand All @@ -105,24 +116,24 @@ where

pub fn exec_transform<F>(cx: CallContext, op: F) -> napi::Result<JsObject>
where
F: FnOnce(&Compiler, String, &Options) -> Result<Arc<SourceFile>, Error>,
F: FnOnce(&Compiler, String, &TransformOptions) -> Result<Arc<SourceFile>, Error>,
{
let c = get_compiler(&cx);

let s = cx.get::<JsString>(0)?.into_utf8()?;
let is_module = cx.get::<JsBoolean>(1)?;
let options: Options = cx.get_deserialized(2)?;
let options: TransformOptions = cx.get_deserialized(2)?;

let output = try_with_handler(c.cm.clone(), |handler| {
c.run(|| {
if is_module.get_value()? {
let program: Program =
serde_json::from_str(s.as_str()?).context("failed to deserialize Program")?;
c.process_js(&handler, program, &options)
c.process_js(&handler, program, &options.swc)
} else {
let fm =
op(&c, s.as_str()?.to_string(), &options).context("failed to load file")?;
c.process_js_file(fm, &handler, &options)
c.process_js_file(fm, &handler, &options.swc)
}
})
})
Expand All @@ -135,10 +146,10 @@ where
pub fn transform(cx: CallContext) -> napi::Result<JsObject> {
schedule_transform(cx, |c, src, _, options| {
let input = Input::Source(c.cm.new_source_file(
if options.filename.is_empty() {
if options.swc.filename.is_empty() {
FileName::Anon
} else {
FileName::Real(options.filename.clone().into())
FileName::Real(options.swc.filename.clone().into())
},
src,
));
Expand All @@ -155,10 +166,10 @@ pub fn transform(cx: CallContext) -> napi::Result<JsObject> {
pub fn transform_sync(cx: CallContext) -> napi::Result<JsObject> {
exec_transform(cx, |c, src, options| {
Ok(c.cm.new_source_file(
if options.filename.is_empty() {
if options.swc.filename.is_empty() {
FileName::Anon
} else {
FileName::Real(options.filename.clone().into())
FileName::Real(options.swc.filename.clone().into())
},
src,
))
Expand Down
10 changes: 9 additions & 1 deletion packages/next/build/swc/src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ DEALINGS IN THE SOFTWARE.
use anyhow::Context;
use napi::{CallContext, JsBuffer, Status};
use serde::de::DeserializeOwned;
use std::any::type_name;

pub trait MapErr<T>: Into<Result<T, anyhow::Error>> {
fn convert_err(self) -> napi::Result<T> {
Expand All @@ -53,7 +54,14 @@ impl CtxtExt for CallContext<'_> {
{
let buffer = self.get::<JsBuffer>(index)?.into_value()?;
let v = serde_json::from_slice(&buffer)
.with_context(|| format!("Argument at `{}` is not JsBuffer", index))
.with_context(|| {
format!(
"Failed to deserialize argument at `{}` as {}\nJSON: {}",
index,
type_name::<T>(),
String::from_utf8_lossy(&buffer)
)
})
.convert_err()?;

Ok(v)
Expand Down
1 change: 1 addition & 0 deletions packages/next/build/webpack-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -291,6 +291,7 @@ export default async function getBaseWebpackConfig(
loader: 'next-swc-loader',
options: {
isServer,
pagesDir,
},
}
: {
Expand Down
12 changes: 9 additions & 3 deletions packages/next/build/webpack/loaders/next-swc-loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ DEALINGS IN THE SOFTWARE.
import { getOptions } from 'next/dist/compiled/loader-utils'
import { transform } from '../../swc'

function getSWCOptions({ isTypeScript, isServer, development }) {
function getSWCOptions({ isTypeScript, isServer, development, isPageFile }) {
const jsc = {
parser: {
syntax: isTypeScript ? 'typescript' : 'ecmascript',
Expand All @@ -52,6 +52,8 @@ function getSWCOptions({ isTypeScript, isServer, development }) {
if (isServer) {
return {
jsc,
// Disables getStaticProps/getServerSideProps tree shaking on the server compilation for pages
disableNextSsg: true,
env: {
targets: {
// Targets the current version of Node.js
Expand All @@ -62,7 +64,7 @@ function getSWCOptions({ isTypeScript, isServer, development }) {
} else {
// Matches default @babel/preset-env behavior
jsc.target = 'es5'
return { jsc }
return { disableNextSsg: !isPageFile, jsc }
}
}

Expand All @@ -74,9 +76,13 @@ async function loaderTransform(parentTrace, source, inputSourceMap) {

let loaderOptions = getOptions(this) || {}

const { isServer, pagesDir } = loaderOptions
const isPageFile = filename.startsWith(pagesDir)

const swcOptions = getSWCOptions({
isTypeScript,
isServer: loaderOptions.isServer,
isServer: isServer,
isPageFile,
development: this.mode === 'development',
})

Expand Down