最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to import a JS file in another JS file in ES6? - Stack Overflow

programmeradmin0浏览0评论

I have got this node server and a bunch of JS classes in my js directory. I want to create a file called "exports.js" that exports all the classes required by server (using exports.Classname = class notation). However, the problem is that exports.js doesn't have access to the classes. I was wondering what's the correct syntax for importing the whole ES6 class in another file. So far I have tried following with no luck:

//I want to import User class from User.js
import "./User.js"; 
import "User";
import "./User";

Any help would be much appreciated.

Note: Not that it makes any difference but please note that I am using Babel transpiler.

I have got this node server and a bunch of JS classes in my js directory. I want to create a file called "exports.js" that exports all the classes required by server (using exports.Classname = class notation). However, the problem is that exports.js doesn't have access to the classes. I was wondering what's the correct syntax for importing the whole ES6 class in another file. So far I have tried following with no luck:

//I want to import User class from User.js
import "./User.js"; 
import "User";
import "./User";

Any help would be much appreciated.

Note: Not that it makes any difference but please note that I am using Babel transpiler.

Share Improve this question edited Dec 17, 2016 at 0:28 fur866 asked Dec 17, 2016 at 0:23 fur866fur866 4132 gold badges5 silver badges14 bronze badges 5
  • If using babel, then import is fine. If not, you have to use require(). Babel transforms import in require() – user2345 Commented Dec 17, 2016 at 0:35
  • Of the three given, what's the correct syntax for import? – fur866 Commented Dec 17, 2016 at 0:38
  • 3 Did you read the MDN documentation? developer.mozilla.org/en/docs/Web/JavaScript/Reference/… . It lists all the possible ways how to import a module. – Felix Kling Commented Dec 17, 2016 at 0:43
  • Use the last one. But first you need to do export default [YOUR CLASS] in the file your define User. – newguy Commented Dec 17, 2016 at 5:03
  • 1 Also, if you want to use / reference the class after import you should use import User from './User', then you can reference it – Ovidiu Dolha Commented Dec 19, 2016 at 8:14
Add a comment  | 

1 Answer 1

Reset to default 18
// user.js
class user{
    ...
}
export default user

// another js
import user from './user.js'
发布评论

评论列表(0)

  1. 暂无评论