diff --git a/.changeset/strong-brooms-dream.md b/.changeset/strong-brooms-dream.md new file mode 100644 index 00000000..4df26f18 --- /dev/null +++ b/.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 diff --git a/packages/cli/src/build/__tests__/basic.ts b/packages/cli/src/build/__tests__/basic.ts index 8c1a9198..481e4c6c 100644 --- a/packages/cli/src/build/__tests__/basic.ts +++ b/packages/cli/src/build/__tests__/basic.ts @@ -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"]` + ); +}); diff --git a/packages/cli/src/rollup-plugins/flow-and-prod-dev-entry.ts b/packages/cli/src/rollup-plugins/flow-and-prod-dev-entry.ts index 1080a8f7..e0300976 100644 --- a/packages/cli/src/rollup-plugins/flow-and-prod-dev-entry.ts +++ b/packages/cli/src/rollup-plugins/flow-and-prod-dev-entry.ts @@ -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[] @@ -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) { @@ -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(