Say I have a file class.js
:
说我有一个文件class.js:
class myClass {
constructor(arg){
console.log(arg);
}
}
And I wanted to use the myClass
class in another file. How would I go about this?
I've tried:var myClass = require('./class.js');
But it didn't work.
I've looked at module.exports
but haven't found an example that works for es6 classes.
我想在另一个文件中使用myClass类。我怎么会这样呢?我试过了:var myClass = require('./ class.js');但它没有用。我查看了module.exports但没有找到适用于es6类的示例。
2 个解决方案
#1
17
Either do
要么这样做
module.exports = class MyClass {
constructor(arg){
console.log(arg);
}
};
and import with
并导入
var a = require("./class.js");
new a("fooBar");
or use the newish syntax (may require you to babelify your code first)
或使用新语法(可能要求您先将代码变为babelify)
export class MyClass {
constructor(arg){
console.log(arg);
}
};
and import with
并导入
import {myClass} from "./class.js";
#2
1
export default class myClass {
constructor(arg){
console.log(arg);
}
}
Other file:
其他档案:
import myClass from './myFile';
#1
17
Either do
要么这样做
module.exports = class MyClass {
constructor(arg){
console.log(arg);
}
};
and import with
并导入
var a = require("./class.js");
new a("fooBar");
or use the newish syntax (may require you to babelify your code first)
或使用新语法(可能要求您先将代码变为babelify)
export class MyClass {
constructor(arg){
console.log(arg);
}
};
and import with
并导入
import {myClass} from "./class.js";
#2
1
export default class myClass {
constructor(arg){
console.log(arg);
}
}
Other file:
其他档案:
import myClass from './myFile';