ES6 module and the module CommonJS What is the difference?

CommonJS difference ES6 Module and Module:
CommonJS shallow copy of the module, the module is ES6 Module references, i.e., only keep ES6 Module read-only, can not change its value, a pointer to the specific point is not changed, similar const
Import interface is read-only (read-only), a variable value which can not be modified. That can not modify its variable pointer to, but you can change the internal pointer variable, can commonJS to reassign (change pointer to),
but ES6 Module assignment will compile error.

<Script type = "text / JavaScript">
             // the CommonJS is shallow copy module 
            // lib.js 
            var counter =. 3 ;
             function incCounter () { 
                counter ++ ; 
            } 
            module.exports = { 
                counter: counter, 
                incCounter: incCounter 
            }; 
            // main.js 
            var MOD = the require ( './ lib' ); 
            
            the console.log (mod.counter);   // . 3 
            mod.incCounter (); 
            the console.log (mod.counter); // . 3
        </script>
        <script type="text/javascript">
            // ES6 Module是对模块的引用
            // lib.js
            export let counter = 3;
            export function incCounter() {
              counter++;
            }
            
            // main.js
            import { counter, incCounter } from './lib';
            console.log(counter); // 3
            incCounter();
            console.log(counter); // 4
        </script>
        <script type="text/javascript">
            // m1.js
            export var foo = 'bar';
            setTimeout(() => foo = 'baz', 500);
            
            // m2.js
            import {foo} from './m1.js';
            console.log(foo); //bar
            setTimeout(() => console.log(foo), 500); //baz
        </script>

CommonJS common modules and ES6 Module:
CommonJS and ES6 Module can not be assigned to the object introduced, i.e., inside the object attribute value change.
But you can add an attribute

<script type="text/javascript">
            // lib.js
            export let obj = {};
            
            // main.js
            import { obj } from './lib';
            
            obj.prop = 123; // OK
            obj = {}; // TypeError
        </script>

Guess you like

Origin www.cnblogs.com/wangxi01/p/11590106.html