1

javascript~引用js的module

 2 years ago
source link: https://www.cnblogs.com/lori/p/16113442.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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>

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK