Reputation: 4170
I'm setting up a class whereby I'm directly importing the package version number into the class as follows:
const pkg = require('../package.json')
export class MyClass() {
constructor() {
// Set the base version from package.json:
this.version = pkg.version
}
}
However, I'm currently getting a little friendly warning from the Typescript ghost in the machine saying that "'require' call may be converted to an import."
I'm assuming that yes it may be possible, but not with a .json file?
Perhaps I should be asking what the best practise for importing a package.json in a .ts file?
Upvotes: 1
Views: 2486
Reputation: 568
You can enable resolveJsonModule
(see TSConfig Reference) in the compilerOptions
of your tsconfig.json and then use an import.
tsconfig.json
{
"compilerOptions": {
"resolveJsonModule" : true,
}
}
myclass.ts
import {version} from ('../package.json');
export class MyClass() {
version: string;
constructor() {
this.version = version
}
}
Upvotes: 4
Reputation: 1046
You can use import
.
import pkg from './package.json';
export default class MyClass {
public version: string;
constructor() {
this.version = pkg.version;
}
}
Just a reminder when you import a module you are making your class dependent on that actual file I'd suggest you to inject the pkg by passing it to constructor.
Upvotes: 1