how to use node.js module system on the clientside

前端 未结 7 1042
感情败类
感情败类 2020-11-27 13:48

I would like to use the CommonJS module system in a clientside javascript application. I chose nodejs as implementation but can\'t find any tutorial or docs on how to use no

7条回答
  •  自闭症患者
    2020-11-27 14:01

    The accepted answer is correct when it comes to RequireJS. But, fast-forward to 2020 and we now have ES modules pretty much on every browser except IE <= 11.

    So, to answer your question "how to use node.js module system on the clientside". Let's start with the fact that you could leverage ES modules already, e.g.

    
    
      
      Hello 2020
      
      
    
    
    
      
          

    Demo

    app.js

    import { hello } from './utils.js'
    
    window.addEventListener('DOMContentLoaded', function (e) {           
        document.getElementsByTagName('h1')[0].innerText = hello('world');
    });
    

    util.js

    function hello(text) {
        return `$hello {text}`;
    }
    
    export { hello };
    

    Now let's assume you want to use an npm package in your browser (assuming this package can run on both browser and node). In that case, you may want to check out Snowpack.

    Snowpack 2.0 is a build system designed for this new era of web development. Snowpack removes the bundler from your dev environment, leveraging native ES Module (ESM) support to serve built files directly to the browser

    In other words, you can use npm packages thus allowing you to use the "node module system" in your client application.

提交回复
热议问题