我爱编程

require与 import

2018-07-26  本文已影响0人  天涯笑笑生

一、exports...require...

const value = 'util'

exports.fun1 = (v) => 'fun1-'+'v:'+v+'-value:'+value
exports.fun2 = (v) => 'fun2-'+'v:'+v+'-value:'+value

people.js file

// 赋值给 `exports` 不会修改模块,必须使用 `module.exports`

module.exports = class People {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }

    toString() {
        return 'name:'+this.name+' age:'+this.age;
    }
}

Test5.js file

//nodejs require 测试

const util = require('./util');
const People = require('./people');

console.log(util.fun1('parameter'))
console.log(util.fun1('parameter'))

const people = new People('Jony', 28);

console.log(people.toString());
require 测试结果

二、export...import...

//按需导入
import {
    Switch,
    HashRouter as Router,
    Route
} from 'react-router-dom';
// 报错
export 1;

// 报错
var m = 1;
export m;

// 写法一
export var m = 1;

// 写法二
var m = 1;
export {m};

// 写法三
var n = 1;
export {n as m};

// 报错
function f() {}
export f;

// 正确
export function f() {};

// 正确
function f() {}
export {f};

export var foo = 'bar';
setTimeout(() => foo = 'baz', 500);

//上面代码输出变量foo,值为bar,500 毫秒之后变成baz
上一篇下一篇

猜你喜欢

热点阅读