为了处理依赖关系 命名空间 等纠结得编程体验 ,(在同一个js文件中引入其他不同的js文件,他们中有相同得方法或变量时候 ,会引起冲突覆盖),
如 在 a.js b.js 中定义了test() 方法 在index.js中通过script标签引入 则后引入得会覆盖前面引入得js文件
因此需要用模块化开发
即1.定义方法 2.暴露方法 在需要使用得地方 3.引用方法
使用
在commonJS规范中 使用 module.exports={} 暴露 使用 const A = require('./js路径') 引入
在ES中写法 使用 export 或export default={} 暴露 使用import {} from ‘./js路径’ 引入
在ES写法中
import * as all from 'module'; 导入所有模块接口 命名为all
import a from 'module'; //导入 默认接口 ,重命名为a ,不加{} 引入, 需要用 export default { a1 } 输出默认接口
import { a1 } from 'module';//导入 module模块中a1接口, 不可重命名, 要加{}引入, 需要export{ a1 }
使用as可以重命名导出或导入得模块名称
常见错误
Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
需要 npm init 创建package.json 设置"type": "commonjs",或 "type": "module", 对应上面不同标准写法