我是 JavaScript 开发新手。我正在使用 npm。
我想生成一些uuid,所以我找到了一个uuid包:
https://www.npmjs.com/package/uuid
我通过运行安装了它
npm 安装 uuid
现在,我想在我的代码中使用这个包。
我发现有两种方法可以做到这一点。 npm 文档建议:
// Generate a v4 UUID (random)
const uuidV4 = require('uuid/v4');
uuidV4(); // -> '110ec58a-a0f2-4ac4-8393-c866d813b8d1'
但我想我也可以这样做(这似乎有效):
import uuid from 'uuid';
console.info(uuid.v4());
我的问题:
- 它们之间有什么区别?
- 我如何知道模块导出什么,以便我知道可以导入什么以及在什么路径下导入?例如,我似乎也可以
import v4 from 'uuid'
...但我不太明白这是如何工作的。
最佳答案
require 是在项目中包含模块的 es5 方式。
导入是在项目中包含模块的 es6 方式。
如果您需要支持旧版浏览器并希望使用 es6 功能,则需要使用 Babel 等转译器将代码转换为 es5 格式。
通过导入,您可以获取模块的各个部分。让我们以此为例:
// test.js
export default () => { console.log("Hi, I'm a default export"); }
export NotDefault = () => { console.log("I am not the default export"); }
现在,如果您尝试:
import NotDefault from "test.js";
您实际上不会导入 NotDefault,而是导入默认导出。
要导入 NotDefault,您可以使用以下格式:
import { NotDefault } from "test.js";
ES5 语法
module.exports = function() {
// this is now the default export of this file.
// you can use this file in another by typing var MyVar = require("module_name");
}
exports.MyFunc = function() {
// this is also exported from this file
// you can use this by var MyVar = require("module_name").myFunc;
}
ES6 语法
default export function() {
// this is the default export of this file
// use can use me by typing import MyVar from "module_name";
}
export const MyFunc = function() {
// this is also exported and can be used by typing
// import { MyFunc } from "module_name";
}
希望这会有所帮助!
关于javascript - 这两种导入 javascript 模块的方法有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43563900/