详谈 import 路径
生活随笔
收集整理的這篇文章主要介紹了
详谈 import 路径
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
import路徑
import {test} from './test';花括號
import {test} from './test'; import test from './test';如果有默認導出export default則可以省略花括號,且import的模塊名是隨意的,如:
// a.js export default 'test';// b.js import a from './a'; import A from './a'; import myA from './a';非export default導出的模板名,在引用時須加花括號,且引用模塊名與導出時的命名必須相同,如:
// a.js export const a = 'test';// b.js import {a} from './a'; import {A} from './a'; // error import {myA} from './a'; // error一個模塊中只允許一個默認導出export default,但允許多個命名導出export;
路徑
import test from 'test'; import test from './test';babel默認會把ES6的模塊轉化為commonjs規范。
import test from 'X'; // 等價于 var test = require('X');查找規則:
如果X是內置模塊,則直接返回該模塊。如require('http')。
如果X以./、/、../開頭:
- 根據X所在的父模塊,確定X的絕對路徑。
- 將X當做文件,依次查找下面的文件,如果找到,則直接返回。
- X
- X.js
- X.json
- X.node
- 將X當做目錄,依次查找下面的文件,如果找到,則直接返回。
- X/package.json(查找main字段中的文件,規則同上)
- X/index.js
- X/index.json
- X/index.node
如果X不帶路徑:
- 根據X所在的父模塊,確定X可能的安裝目錄。
- 依次在每個目錄中,將X當成文件名或目錄名加載。
"not found"
模塊格式
CommonJS
同步加載模塊,主要用于服務端(node)。
// math.js exports.add = function(a, b) {return a + b; }// main.js var math = require('./math'); math.add(2, 3); // 5AMD
異步模塊定義,用于像RequireJS這樣的模塊加載器,主要用于瀏覽器。
// math.js define(function() {var add = function(x, y) {return x + y;}return {add: add} })// main.js require(['math'], function(math) {alert(math.add(1, 1)); })UMD
(function (root, factory) {if (typeof define === 'function' && define.amd) {// AMD. Register as an anonymous module.define([], factory);} else if (typeof module === 'object' && module.exports) {// Node. Does not work with strict CommonJS, but// only CommonJS-like environments that support module.exports,// like Node.module.exports = factory();} else {// Browser globals (root is window)root.returnExports = factory();} }(typeof self !== 'undefined' ? self : this, function () {// Just return a value to define the module export.// This example returns an object, but the module// can return a function as the exported value.return {}; }));ES6
es6通過import、export實現模塊的輸入輸出
參考資料
when-should-i-use-curly-braces-for-es6-import
what require.resolve() does
UMD
總結
以上是生活随笔為你收集整理的详谈 import 路径的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java instant_Java In
- 下一篇: ubuntu系统启动项的修改