javascript~引用js的module


我们知道,在script标签中写js代码,或者使用src引入js文件时,默认不能使用module形式,即不能使用import导入文件,但是我们可以再script标签上加上type=module属性来改变方式。

  • 使用方法如下:
  • js引用js
    //module.js
    export default function test(){
      return 'test...'
    }

    // index.js
    import test from './module.js';
    console.log(test())
  • html页面引用js
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Document</title>
    </head>
    <body>
      // 方法 1 : 引入module.js,然后在script标签里面调用
      <script type="module">
        import test from './module.js';
        console.log(test())
      </script>
     
      // 方法 2 : 直接引入index.js,使用src引入
      <script type="module" src="./index.js"></script>
     
    </body>
    </html>


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM