javascript 导入,要求和导出

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 导入,要求和导出相关的知识,希望对你有一定的参考价值。

// require() is used to import functions and code from external files
// The problem is, if the file is large and has many functions, it imports the whole file. Not handy if
// you're only wanting to import one or two functions.

// ------------ //
// -- Import -- //
// ------------ //
// we can choose which parts of a module or file to load into a given file, saving time and memory.
import { countItems } from "math_array_functions" 
import { variable } from "file_path_goes_here" // imports a variable

// Use * to Import Everything from a File
// You may use any name following the import * as portion of the statement. 
// In order to utilize this method, it requires an object that receives the imported values. 
// From here, you will use the dot notation to call your imported values.

// syntax
import * as object_with_name_of_your_choice from "file_path_goes_here"
object_with_name_of_your_choice.imported_function
// example
import * as myObj from 'filepath';
myObj.add(2, 3);
myObj.subtract(2, 5);

// ------------ //
// -- Export -- //
// ------------ //
// to be able to import a piece of code, you must export it first
const capitalizeString = (string) => {
  return string.charAt(0).toUpperCase() + string.slice(1);
}
// NAMED EXPORTS
const foo = "bar";
export { capitalizeString, foo };

// EXPORT DEFAULT
// Usually you will use this syntax if only one value is being exported from a file. 
// It is also used to create a fallback value for a file or module.
// you can only have one value be a default export in each module or file.
// Additionally, you cannot use export default with var, let, or const
export default function subtract(x,y) {return x - y;}

// IMPORT A DEFAULT EXPORT
// syntax 
import add from "math_functions";
add(5, 4);

以上是关于javascript 导入,要求和导出的主要内容,如果未能解决你的问题,请参考以下文章

导入和导出javascript [重复]

通过导入和导出制作最少的工作 JavaScript 代码

javascript 导出和导入模块

javascript 模块化(导入和导出文件)

javascript javascript导入导出

如何在 JavaScript 中使用SpreadJS导入和导出 Excel 文件