2.1 KiB
2.1 KiB
id, challengeType, forumTopicId, localeTitle
id | challengeType | forumTopicId | localeTitle |
---|---|---|---|
587d7b8c367417b2b2512b55 | 1 | 301208 | 通过 import 复用 JavaScript 代码 |
Description
import
可以导入文件或模块的一部分。在之前的课程里,例子从 math_functions.js
文件里导出了 add
,下面看一下如何在其它的文件导入它:
import { add } from './math_functions.js';
在这里,import
会在 math_functions.js
里找到 add
,只导入这个函数,忽略剩余的部分。./
告诉程序在当前文件的相同目录寻找 math_functions.js
文件。用这种方式导入时,相对路径(./
)和文件扩展名(.js
)都是必需的。
可以在导入语句里导入多个项目,如下:
import { add, subtract } from './math_functions.js';
Instructions
import
语句,使当前文件可以使用你在之前课程里导出的 uppercaseString
和 lowercaseString
函数,函数在当前路径下的 string_functions.js
文件里。
Tests
tests:
- text: 应该导入 <code>uppercaseString</code>、
testString: assert(code.match(/import\s*{\s*(uppercaseString[^}]*|[^,]*,\s*uppercaseString\s*)}\s+from\s+('|")\.\/string_functions\.js\2/g));
- text: 应该导入 <code>lowercaseString</code>、
testString: assert(code.match(/import\s*{\s*(lowercaseString[^}]*|[^,]*,\s*lowercaseString\s*)}\s+from\s+('|")\.\/string_functions\.js\2/g));
Challenge Seed
// add code above this line
uppercaseString("hello");
lowercaseString("WORLD!");
Solution
import { uppercaseString, lowercaseString } from './string_functions.js';
// add code above this line
uppercaseString("hello");
lowercaseString("WORLD!");