Unverified Commit e725f8f7 authored by Jimmy Miller's avatar Jimmy Miller Committed by GitHub

[turbopack] Support webpack loader build dependency requests (#99071)

Adds support for resolving build dependencies to modules (cjs or mjs)
the way that webpack does. There is more support, but this was a nice
isolatable slice.
parent 2f3cb719
import { utilFn } from '../../utils/esm-build-dependency'
export default function Page() {
return <p>{utilFn()}</p>
}
import { utilFn } from '../../utils/package-build-dependency'
export default function Page() {
return <p>{utilFn()}</p>
}
{
"name": "build-dependency-esm-package",
"version": "1.0.0",
"exports": {
"./conditional.mjs": {
"import": "./import.mjs",
"require": "./require.cjs"
}
}
}
...@@ -32,6 +32,35 @@ const loader = async function (content) { ...@@ -32,6 +32,35 @@ const loader = async function (content) {
) )
} }
if (this.resourcePath.endsWith('package-build-dependency.ts')) {
const packageEntry = require.resolve('build-dependency-package')
this.addBuildDependency('build-dependency-package')
const packageValue = fs
.readFileSync(packageEntry, 'utf8')
.match(/'([^']+)'/)[1]
return this.callback(
null,
`export const utilFn = () => 'package build dependency: ${packageValue}, generated at ${new Date().toISOString()}';`
)
}
if (this.resourcePath.endsWith('esm-build-dependency.ts')) {
const packageEntry = path.join(
__dirname,
'node_modules',
'build-dependency-esm-package',
'import.mjs'
)
this.addBuildDependency('build-dependency-esm-package/conditional.mjs')
const packageValue = fs
.readFileSync(packageEntry, 'utf8')
.match(/'([^']+)'/)[1]
return this.callback(
null,
`export const utilFn = () => 'ESM build dependency: ${packageValue}, generated at ${new Date().toISOString()}';`
)
}
if (!this.resourcePath.endsWith('file-to-transform.ts')) { if (!this.resourcePath.endsWith('file-to-transform.ts')) {
return this.callback(null, content) return this.callback(null, content)
} }
......
...@@ -5,6 +5,9 @@ const path = require('node:path') ...@@ -5,6 +5,9 @@ const path = require('node:path')
*/ */
const nextConfig = { const nextConfig = {
turbopack: { turbopack: {
resolveAlias: {
'build-dependency-package': './aliased-build-dependency.js',
},
rules: { rules: {
'*.ts': { '*.ts': {
loaders: [path.resolve(__dirname, './loader.js')], loaders: [path.resolve(__dirname, './loader.js')],
...@@ -12,6 +15,10 @@ const nextConfig = { ...@@ -12,6 +15,10 @@ const nextConfig = {
}, },
}, },
webpack: (config) => { webpack: (config) => {
config.resolve.alias['build-dependency-package'] = path.resolve(
__dirname,
'./aliased-build-dependency.js'
)
config.module.rules.push({ config.module.rules.push({
test: /\.ts$/, test: /\.ts$/,
use: [path.resolve(__dirname, './loader.js')], use: [path.resolve(__dirname, './loader.js')],
......
...@@ -4,6 +4,10 @@ import { retry } from 'next-test-utils' ...@@ -4,6 +4,10 @@ import { retry } from 'next-test-utils'
describe('turbopack-loader-file-dependencies', () => { describe('turbopack-loader-file-dependencies', () => {
const { next } = nextTestSetup({ const { next } = nextTestSetup({
files: __dirname, files: __dirname,
dependencies: {
'build-dependency-esm-package': 'file:./build-dependency-esm-package',
'build-dependency-package': 'file:./build-dependency-package',
},
}) })
it('should update when the dependency file changes', async () => { it('should update when the dependency file changes', async () => {
...@@ -57,6 +61,52 @@ describe('turbopack-loader-file-dependencies', () => { ...@@ -57,6 +61,52 @@ describe('turbopack-loader-file-dependencies', () => {
) )
}) })
// @force-gate turbopack
it('updates when a package entry added as a build dependency changes', async () => {
const $ = await next.render$('/package')
expect($('p').text()).toContain('package build dependency: package-one')
await next.patchFile(
'node_modules/build-dependency-package/one.js',
"module.exports = 'package-two'",
async () => {
await retry(async () => {
const $2 = await next.render$('/package')
expect($2('p').text()).toContain(
'package build dependency: package-two'
)
}, 10000)
}
)
await retry(async () => {
const $2 = await next.render$('/package')
expect($2('p').text()).toContain('package build dependency: package-one')
}, 10000)
})
// @force-gate turbopack
it('resolves .mjs build dependencies with ESM conditions', async () => {
const $ = await next.render$('/mjs')
expect($('p').text()).toContain('ESM build dependency: import-one')
await next.patchFile(
'node_modules/build-dependency-esm-package/import.mjs',
"export default 'import-two'",
async () => {
await retry(async () => {
const $2 = await next.render$('/mjs')
expect($2('p').text()).toContain('ESM build dependency: import-two')
}, 10000)
}
)
await retry(async () => {
const $2 = await next.render$('/mjs')
expect($2('p').text()).toContain('ESM build dependency: import-one')
}, 10000)
})
// @force-gate turbopack // @force-gate turbopack
it('warns for unsupported build dependency inputs', async () => { it('warns for unsupported build dependency inputs', async () => {
await next.symlink('cyclic-build-dependency', 'cyclic-build-dependency') await next.symlink('cyclic-build-dependency', 'cyclic-build-dependency')
......
...@@ -40,6 +40,7 @@ use turbopack_core::{ ...@@ -40,6 +40,7 @@ use turbopack_core::{
reference_type::{EcmaScriptModulesReferenceSubType, InnerAssets, ReferenceType}, reference_type::{EcmaScriptModulesReferenceSubType, InnerAssets, ReferenceType},
resolve::{ resolve::{
ResolveErrorMode, ResolveErrorMode,
node::{node_cjs_resolve_options, node_esm_resolve_options},
options::{ConditionValue, ResolveInPackage, ResolveIntoPackage, ResolveOptions}, options::{ConditionValue, ResolveInPackage, ResolveIntoPackage, ResolveOptions},
origin::PlainResolveOrigin, origin::PlainResolveOrigin,
parse::Request, parse::Request,
...@@ -325,7 +326,53 @@ async fn build_dependency_requests_changed( ...@@ -325,7 +326,53 @@ async fn build_dependency_requests_changed(
source: ResolvedVc<Box<dyn Source>>, source: ResolvedVc<Box<dyn Source>>,
) -> Result<Vc<Completion>> { ) -> Result<Vc<Completion>> {
for (request, is_directory) in requests { for (request, is_directory) in requests {
let path = cwd.join(&request)?; let request_path = cwd.join(&request)?;
if matches!(
&*request_path.get_type().await?,
FileSystemEntryType::Symlink
) {
BuildDependencyIssue {
source: IssueSource::from_source_only(source),
path: request_path,
}
.resolved_cell()
.emit();
continue;
}
let path = if is_directory {
request_path.clone()
} else {
let parsed_request = Request::parse(Pattern::Constant(request.clone()));
let options = if request.ends_with(".mjs") {
node_esm_resolve_options()
} else {
node_cjs_resolve_options()
};
let resolved = resolve(
cwd.clone(),
ReferenceType::Undefined,
parsed_request,
options,
);
let (resolved_source, error) = match resolved.await {
Ok(result) => {
assert!(result.primary_sources().count() <= 1);
(result.first_source(), None)
}
Err(error) => (None, Some(format!("{error:#}").into())),
};
let Some(resolved_source) = resolved_source else {
UnresolvedBuildDependencyIssue {
source: IssueSource::from_source_only(source),
request,
error,
}
.resolved_cell()
.emit();
continue;
};
resolved_source.ident().await?.path.clone()
};
let entry_type = path.get_type().await?; let entry_type = path.get_type().await?;
let supported = match &*entry_type { let supported = match &*entry_type {
FileSystemEntryType::File if !is_directory => { FileSystemEntryType::File if !is_directory => {
...@@ -1167,8 +1214,8 @@ impl Issue for BuildDependencyIssue { ...@@ -1167,8 +1214,8 @@ impl Issue for BuildDependencyIssue {
StyledString::Text(rcstr!("The path at ")), StyledString::Text(rcstr!("The path at ")),
StyledString::Code(self.path.to_string().into()), StyledString::Code(self.path.to_string().into()),
StyledString::Text( StyledString::Text(
" is not an exact existing file or explicit directory build dependency. \ " is not a supported file or explicit directory build dependency. Unsupported \
Unsupported inputs may require restarting the development server." inputs may require restarting the development server."
.into(), .into(),
), ),
]))) ])))
...@@ -1179,6 +1226,53 @@ impl Issue for BuildDependencyIssue { ...@@ -1179,6 +1226,53 @@ impl Issue for BuildDependencyIssue {
} }
} }
#[turbo_tasks::value(shared)]
pub struct UnresolvedBuildDependencyIssue {
pub request: RcStr,
pub error: Option<RcStr>,
pub source: IssueSource,
}
#[async_trait]
#[turbo_tasks::value_impl]
impl Issue for UnresolvedBuildDependencyIssue {
fn severity(&self) -> IssueSeverity {
IssueSeverity::Warning
}
async fn title(&self) -> Result<StyledString> {
Ok(StyledString::Text(rcstr!(
"Unable to resolve webpack loader build dependency"
)))
}
fn stage(&self) -> IssueStage {
IssueStage::Resolve
}
async fn file_path(&self) -> Result<FileSystemPath> {
self.source.file_path().await
}
async fn description(&self) -> Result<Option<StyledString>> {
let mut description = vec![
StyledString::Text(rcstr!("The build dependency request ")),
StyledString::Code(self.request.clone()),
StyledString::Text(rcstr!(" could not be resolved to a file.")),
];
if let Some(error) = &self.error {
description.push(StyledString::Text(
format!(" Resolver error: {error}").into(),
));
}
Ok(Some(StyledString::Line(description)))
}
fn source(&self) -> Option<IssueSource> {
Some(self.source)
}
}
#[turbo_tasks::value(shared)] #[turbo_tasks::value(shared)]
pub struct EvaluateEmittedErrorIssue { pub struct EvaluateEmittedErrorIssue {
pub source: IssueSource, pub source: IssueSource,
......
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