Skip to content

Fix/remove type imports typescript #164

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

Merged
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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
## [3.9.3](https://github.com/kaisermann/svelte-preprocess/compare/v3.9.2...v3.9.3) (2020-06-06)



## [3.9.2](https://github.com/kaisermann/svelte-preprocess/compare/v3.7.4...v3.9.2) (2020-06-06)


Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -659,3 +659,5 @@ import preprocess from 'svelte-preprocess'
}
...
```

Warning: If you do this, you can't import types or interfaces into your svelte component without using the new TS 3.8 `type` import modifier: `import type { SomeInterface } from './MyModule.ts'` otherwise Rollup (and possibly others) will complain that the name is not exported by `MyModule`)
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "svelte-preprocess",
"version": "3.9.2",
"version": "3.9.3",
"license": "MIT",
"main": "dist/index.js",
"types": "dist/index.d.ts",
Expand Down
96 changes: 94 additions & 2 deletions src/transformers/typescript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,10 @@ function isValidSvelteImportDiagnostic(filename: string, diagnostic: any) {
const importTransformer: ts.TransformerFactory<ts.SourceFile> = (context) => {
const visit: ts.Visitor = (node) => {
if (ts.isImportDeclaration(node)) {
if (node.importClause?.isTypeOnly) {
return ts.createEmptyStatement();
}

return ts.createImportDeclaration(
node.decorators,
node.modifiers,
Expand Down Expand Up @@ -112,6 +116,89 @@ function isValidSvelteReactiveValueDiagnostic(
return !(usedVar && proposedVar && usedVar === proposedVar);
}

function createImportTransformerFromProgram(program: ts.Program) {
const checker = program.getTypeChecker();

const importedTypeRemoverTransformer: ts.TransformerFactory<ts.SourceFile> = (
context,
) => {
const visit: ts.Visitor = (node) => {
if (!ts.isImportDeclaration(node)) {
return ts.visitEachChild(node, (child) => visit(child), context);
}

let newImportClause: ts.ImportClause = node.importClause;

if (node.importClause) {
// import type {...} from './blah'
if (node.importClause?.isTypeOnly) {
return ts.createEmptyStatement();
}

// import Blah, { blah } from './blah'
newImportClause = ts.getMutableClone(node.importClause);

// types can't be default exports, so we just worry about { blah } and { blah as name } exports
if (
newImportClause.namedBindings &&
ts.isNamedImports(newImportClause.namedBindings)
) {
const newBindings = ts.getMutableClone(newImportClause.namedBindings);
const newElements = [];

newImportClause.namedBindings = undefined;

for (const spec of newBindings.elements) {
const ident = spec.name;

const symbol = checker.getSymbolAtLocation(ident);
const aliased = checker.getAliasedSymbol(symbol);

if (aliased) {
if (
(aliased.flags &
(ts.SymbolFlags.TypeAlias | ts.SymbolFlags.Interface)) >
0
) {
// We found an imported type, don't add to our new import clause
continue;
}
}
newElements.push(spec);
}

if (newElements.length > 0) {
newBindings.elements = ts.createNodeArray(
newElements,
newBindings.elements.hasTrailingComma,
);
newImportClause.namedBindings = newBindings;
}
}

// we ended up removing all named bindings and we didn't have a name? nothing left to import.
if (
newImportClause.namedBindings == null &&
newImportClause.name == null
) {
return ts.createEmptyStatement();
}
}

return ts.createImportDeclaration(
node.decorators,
node.modifiers,
newImportClause,
node.moduleSpecifier,
);
};

return (node) => ts.visitNode(node, visit);
};

return importedTypeRemoverTransformer;
}

function compileFileFromMemory(
compilerOptions: CompilerOptions,
{ filename, content }: { filename: string; content: string },
Expand Down Expand Up @@ -172,12 +259,17 @@ function compileFileFromMemory(
};

const program = ts.createProgram([dummyFileName], compilerOptions, host);

const transformers = {
before: [createImportTransformerFromProgram(program)],
};

const emitResult = program.emit(
program.getSourceFile(dummyFileName),
undefined,
undefined,
undefined,
undefined,
TS_TRANSFORMERS,
transformers,
);

// collect diagnostics without svelte import errors
Expand Down
7 changes: 7 additions & 0 deletions test/fixtures/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export type AType = "test1" | "test2"
export interface AInterface {
test: string
}
export const AValue: string = "test"

export default "String"
44 changes: 44 additions & 0 deletions test/transformers/typescript.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -175,5 +175,49 @@ describe('transformer - typescript', () => {

expect(diagnostics.some((d) => d.code === 2552)).toBe(true);
});

it('should remove imports containing types only', async () => {
const { code } = await transpile(
`
import { AType, AInterface } from './fixtures/types'
let name: AType = "test1";
`,
);

expect(code).not.toContain('/fixtures/types');
});

it('should remove type only imports', async () => {
const { code } = await transpile(
`
import type { AType, AInterface } from './fixtures/types'
let name: AType = "test1";
`,
);

expect(code).not.toContain('/fixtures/types');
});

it('should remove only the types from the imports', async () => {
const { code } = await transpile(
`
import { AValue, AType, AInterface } from './fixtures/types'
let name: AType = "test1";
`,
);

expect(code).toContain("import { AValue } from './fixtures/types'");
});

it('should remove the named imports completely if they were all types', async () => {
const { code } = await transpile(
`
import Default, { AType, AInterface } from './fixtures/types'
let name: AType = "test1";
`,
);

expect(code).toContain("import Default from './fixtures/types'");
});
});
});