关于export、import、exports 、require的使用方法介绍

准备工作:新建test.js、test2.js 、A页面

1、分别暴露与引用

导出

/**
* test.js 导出变量strVal、与函数fun
* @param strVal
* @param func
*/
export let strVal = '这是例子里的变量'
export function fun(){
  console.log("这是例子里的函数")
  return "这是例子里的函数"
}

引用

/**
* 需要使用的页面 b
* 引入 import { strVal , fun } from " test.js(文件路径)"
*/
import { strVal , fun } from 'test.js';

console.log('函数====',fun())
console.log('变量====',strVal)

2、统一暴露与引用

导出

/**
* test.js 定义变量strVal  和函数func,统一暴露出去
* @param strVal
* @param func
*/
let strVal = '这是例子里的变量'
function fun (){
  console.log("这是例子里的函数")
  return '这是例子里的函数'
}
export { strVal , fun }

引用

/**
* 需要使用的页面 b
* 引入 import { strVal , fun } from " test.js(文件路径)"
* 若某些变量或函数在import导入时不需要,可以不在{ }中定义
*/
import { strVal , fun } from 'test.js';

console.log('函数====',fun())
console.log('变量====',strVal)

3、默认暴露与引用

1)、导出

/**
* test.js 默认暴露一个函数 fun
*/
export default function fun(){
    return "这是例子里的函数"
}

1)、引用

/**
* 需要使用的页面 b
* 引入 import fun  from 'test.js(文件路径)';
*/
import fun  from 'test.js';

console.log('函数====',fun())

2)、导出

/**
* test.js 默认暴露一个变量strVal 和函数fun
*/
let strVal = '这是例子里的变量'
function fun(){
    return "这是例子里的函数"
}
export default { strVal , fun }

2)、引用

/**
* 需要使用的页面 b
* 如要引入的js模块默认暴露的是一个对象
* 引入 import aFunc  from 'test.js(文件路径)';
*/
import testFn from 'test.js';
console.log('例子====',testFn.strVal)
console.log('例子====',testFn.fun())

4、通配符 * 批量引用暴露

导出

/**
* test.js 暴露一个变量a 和函数fun
*/
export let strVal = '这是例子里的变量'
export function fun(){
    return "这是例子里的函数"
}

引用

/**
* 需要使用的页面 b
* 引入 import * as testFn  from 'test.js(文件路径)';
*/
import * as testFn  from 'test.js';
console.log('例子====',testFn.strVal)
console.log('例子====',testFn.fun())

5、如果引入的模块有相同的名字利用as重命名

导出

/**
* 分别暴露函数fun、fun2
*/
// test.js
export function fun(){
  return "这是test.js"
}

// test2.js
export function fun(){
  return "这是test2.js"
}

引用

/**
* 需要使用的页面 b
* 分别引入 test.js、test2.js
*/
import fun from 'test.js'
//import {原来的函数名字 as 重新起的别名} from 'test2.js(文件路径)'
import {fun as fun2}  from 'test2.js';
console.log('test.js的值====',fun)
console.log('test2.js的值====',fun2)

关于export、import介绍官方地址:

export - JavaScript | MDN

import - JavaScript | MDN

6、module.exports 与 exports

exports 等于 module.exports,相当于在js文件头部有一个module的对象,

module.exports = exports;

exports是一个对象,可以exports多个值

导出

/**
* test.js 暴露一个变量a 和函数fun
*/
exports.strVal = '这是例子里的变量';
exports.fun= function(a=1){
    return "这是例子里的函数===参数(可加可不加,这里默认1):" +a
}

引用

/**
* 需要使用的页面 b
* 引入 test.js
*/
let fun = require('test.js');

console.log('test.js的值====',fun.strVal)
console.log('test.js的值====',fun.fun(2))

详细介绍官方文档:Modules: CommonJS modules | Node.js v16.19.0 Documentation

你可能感兴趣的:(javascript学习笔记,javascript,前端,vue.js,import,export)