Allow importing .ts files with .js extension (#3518)

* Allow importing .ts files with .js extension

* Adds a changeset

* Make it also work in .md files
This commit is contained in:
Matthew Phillips 2022-06-03 13:00:28 -04:00 committed by GitHub
parent d9a67d36dc
commit df7c43df63
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
8 changed files with 65 additions and 0 deletions

View file

@ -0,0 +1,5 @@
---
'astro': patch
---
Allow importing .ts files with .js extension

View file

@ -216,6 +216,13 @@ export default function astro({ config, logging }: AstroPluginOptions): vite.Plu
return {
code: `${code}${SUFFIX}`,
map,
meta: {
vite: {
// Setting this vite metadata to `ts` causes Vite to resolve .js
// extensions to .ts files.
lang: 'ts'
}
}
};
} catch (err: any) {
// Verify frontmatter: a common reason that this plugin fails is that

View file

@ -194,6 +194,11 @@ ${tsResult}`;
return {
code: escapeViteEnvReferences(code),
map: null,
meta: {
vite: {
lang: 'ts'
}
}
};
}

View file

@ -0,0 +1,3 @@
export default function() {
return 'bar';
}

View file

@ -0,0 +1,3 @@
import bar from './bar.js';
export default bar;

View file

@ -0,0 +1,9 @@
---
import foo from '../foo.js';
---
<html>
<head><title></title></head>
<body>
<h1>{ foo() }</h1>
</body>
</html>

View file

@ -0,0 +1,8 @@
---
setup: |
import foo from '../foo.js'
---
# Testing
## { foo() }

View file

@ -0,0 +1,25 @@
import { expect } from 'chai';
import * as cheerio from 'cheerio';
import { loadFixture } from './test-utils.js';
describe('Using .js extension on .ts file', () => {
/** @type {import('./test-utils').Fixture} */
let fixture;
before(async () => {
fixture = await loadFixture({ root: './fixtures/import-ts-with-js/' });
await fixture.build();
});
it('works in .astro files', async () => {
const html = await fixture.readFile('/index.html');
const $ = cheerio.load(html);
expect($('h1').text()).to.equal('bar');
});
it('works in .md files', async () => {
const html = await fixture.readFile('/post/index.html');
const $ = cheerio.load(html);
expect($('h2').text()).to.equal('bar');
});
});