Skip to content

Commit

Permalink
Improve error when importing something with an extension that can't b…
Browse files Browse the repository at this point in the history
…e imported
  • Loading branch information
emmatown committed Jul 28, 2022
1 parent a2c05e1 commit eaa2fcc
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 6 deletions.
5 changes: 5 additions & 0 deletions .changeset/strong-brooms-dream.md
@@ -0,0 +1,5 @@
---
"@preconstruct/cli": patch
---

Improved error when importing something with an extension that can't be imported
17 changes: 17 additions & 0 deletions packages/cli/src/build/__tests__/basic.ts
Expand Up @@ -1197,3 +1197,20 @@ test("node: is external", async () => {
`);
});

test("importing css fails with a nice error", async () => {
let dir = await testdir({
"package.json": JSON.stringify({
name: "@scope/test",
main: "dist/scope-test.cjs.js",
module: "dist/scope-test.esm.js",
}),
"src/index.js": js`
import "./blah.css";
`,
"src/blah.css": "",
});
await expect(build(dir)).rejects.toMatchInlineSnapshot(
`[Error: 🎁 @scope/test only .ts, .tsx, .js, .jsx, and .json files can be imported but "./blah.css" is imported in "src/index.js"]`
);
});
27 changes: 21 additions & 6 deletions packages/cli/src/rollup-plugins/flow-and-prod-dev-entry.ts
Expand Up @@ -8,6 +8,8 @@ import { FatalError } from "../errors";
import * as fs from "fs-extra";
import normalizePath from "normalize-path";

const allowedExtensionRegex = /\.([tj]sx?|json)$/;

export default function flowAndNodeDevProdEntry(
pkg: Package,
warnings: FatalError[]
Expand All @@ -21,7 +23,7 @@ export default function flowAndNodeDevProdEntry(
return null;
},
async resolveId(source, importer) {
let resolved = await this.resolve(source, importer!, {
let resolved = await this.resolve(source, importer, {
skipSelf: true,
});
if (resolved === null) {
Expand All @@ -47,11 +49,24 @@ export default function flowAndNodeDevProdEntry(
);
}

if (
source.startsWith("\0") ||
resolved.id.startsWith("\0") ||
resolved.id.startsWith(pkg.directory)
) {
if (source.startsWith("\0") || resolved.id.startsWith("\0")) {
return resolved;
}
if (resolved.id.startsWith(pkg.directory)) {
if (!resolved.external && !allowedExtensionRegex.test(resolved.id)) {
warnings.push(
new FatalError(
`only .ts, .tsx, .js, .jsx, and .json files can be imported but "${source}" is imported in ${
importer
? `"${normalizePath(path.relative(pkg.directory, importer))}"`
: "a module"
}`,
pkg.name
)
);
return "could-not-resolve";
}

return resolved;
}
warnings.push(
Expand Down

0 comments on commit eaa2fcc

Please sign in to comment.