Request: compiler option to disable elision of "unused" imports · Issue #18586 · microsoft/TypeScript (original) (raw)
I'd love to see a compiler option that allows us to disable the elision of unused imports.
I am using a Babel plugin that translates the pug into React createElement
statements, so I can use the compact/readable pug language instead of JSX. The babel plugin runs after the typescript compiler.
As shown in the code (app.ts
) below, I import a React component (component.ts
) using an import
statement. The babel plugin will convert a pug-style JSX declaration into the React.createElement
call as appropriate. However the imported components are no-longer visible as typescript has dropped the associated imports because it did not see them being used.
Incorporating a compiler option to disable this "optimization" is desired.
TypeScript Version: 2.5.2
Code
The @types/babel-plugin-react-pug
package is a prerequisite for the code below.
[component.ts]
A standard React component exported asComponent
.
import * as React from "react";
export
class Component extends React.Component {
public render() {
// The babel-plugin-react-pug babel plugin converts this
// to React.createElement("p", null, "Hello world from Component.")
return pug p Hello world from Component.
;
}
}
[app.ts]
A React app/container that imports the above component and includes it as a child.
import * as React from "react";
// This does not work because typescript removes the import //import { Component } from "component";
// Workaround: force typescript to keep the import, without renaming "Component" import { Component as _Component } from "component"; const Component = _Component;
class App extends React.Component {
public render() {
// The babel-plugin-react-pug babel plugin converts this
// to React.createElement(Component, null)
return pug Component
;
}
}
Expected behavior:
The workaround given above should be replaced by a compiler option to disable the import elision; the import code above then reduces to the regular (simple) import statement:
import { Component } from "component";
Secondly, the typescript compiler should not rename the Component
symbol. (I have noticed that sometimes, but not always, the typescript compiler will rename imported symbols.)
Actual behavior:
The typescript compiler removes the import statement, so the Component
symbol is not emitted into the compiled JavaScript.
After babel runs the babel-plugin-react-pug
plugin, and replaces the pug source with React.createElement(Component, null)
, JavaScript declares that it cannot find the symbol Component
(because typescript dropped it).