【问题标题】:Using import or require in the browser file在浏览器文件中使用 import 或 require
【发布时间】:2021-01-21 11:46:39
【问题描述】:

我正在使用 react 和 nextjs 为 Shopify 商店开发我的应用程序。在这个应用程序中,我正在创建一个脚本标签(SHOPIFY API),它向店面添加一些功能并从那里存储一些数据。现在,我想将该数据存储在需要导入或需要某些节点模块的某个文件中,但是当我使用“import”语句时,它给了我“不能在模块外使用导入”和使用“require”语句给我“未定义要求”错误。 我在网上搜索并找到了使用“Browserify”的解决方案。但是,在 browserify 中,当我没有任何 html 文件时,它们在 html 文件中包含脚本。我想将js文件加载到js文件中。

scripttag.js(我想在文件中包含文件系统和 firebase-admin)

var fs = require('fs');
console.log('this is me script tag!!!!!!!!')
const header = $('header.site-header').parent();

header.prepend('<div>Hello this is coming from the public folder </div>').css({'background-color':'orange', 'text-align': 'center'})

function addWishList(customer, productid){
/*
  fetch(`url`, {
    method: 'POST',
    headers: {
      'Content-Type': ,
      "X-Shopify-Access-Token": ,
    },
    body: 
    }})
  })

*/

    console.log('adding item to the wishlist!!')
}

function removeWishList(){
    console.log('removing item from the wishlist!!')
}

// const b1 = $('button.wishlist-btn');
// b1.on("click", addWishList);
 var wishbtn = document.querySelector('.wishlist-btn')
 wishbtn.addEventListener('click', function(){
     if(this.classList.contains('active')){             //condition to check if the button is already pressed
        removeWishList();
        this.classList.remove('active');
        this.innerHTML = 'Add to wishlist'
     }
     else{
        var customer = wishbtn.dataset.customer;
        if(customer == null || customer == ''){
            console.log('bhai log in kro')
        }
        else{
            var productid = wishbtn.dataset.product;
            this.classList.add('active');      //when the user presses add to wishlist button, it add active to the button's class
            this.innerHTML = 'Remove from wishlist'
            addWishList(customer, productid);
        }
       
   //     console.log(customer);
   //     console.log(productid)
        
  //      wishbtn.innerHTML= 'added to the wishlisht'
     }
     
 })

【问题讨论】:

  • 坏消息是:你不能在浏览器中使用 fs 模块...好消息是:&lt;script type="module"&gt; 在那里启用了 ESM。
  • 是的,但是当我使用 type = "module" 时,我在浏览器中收到 CORS 阻止错误

标签: javascript node.js reactjs shopify node-modules


【解决方案1】:

您可以通过将加载文件时使用的&lt;script&gt; 标签更改为启用 ES 模块

<script type="module" src="<your scriptfile"></script>

【讨论】:

  • 实际上,我不使用这个脚本标签加载我的文件。相反,我使用的是 Shopify 的 SCRIPT_TAG API,它将远程 JavaScript 加载到商店的店面中。这样,我可以在我的应用中访问商店的元素。
猜你喜欢
  • 2013-11-13
  • 2017-03-05
  • 2020-10-21
  • 2013-05-14
  • 1970-01-01
  • 2017-08-24
  • 1970-01-01
  • 2016-07-17
相关资源
最近更新 更多