【问题标题】:can not load javascript class inside node modules in webpack无法在 webpack 的节点模块中加载 javascript 类
【发布时间】:2019-06-26 02:05:41
【问题描述】:

我已经创建并发布了一个自定义 npm 包,并将该包包含在我的 webapck 入口文件中。但是我无法在我的 html 文件中调用该 npm 类中的函数。这是我的 npm 包

 export default class myClass{
        constructor(getVar){
            this.params     =   {
                signLength : (getVar.signLength !=undefined)?getVar.signLength:null,
                canvas     : (getVar.canvas !=undefined)?getVar.canvas:null,
                linecolor  : (getVar.linecolor !=undefined)?getVar.linecolor:null,
                pointSize  : (getVar.pointSize !=undefined)?getVar.pointSize:null,
                xstarting  : '',
                ystarting  : ''
            }; 
...........................

我已经将它包含在我的 webpack 入口文件中

const myClass = require('npm pack name').default;
module.exports = myClass;

我正在尝试在我的 html 文件中调用它

setParams.canvas.addEventListener("mousemove", function(e){
    myClass.draw(e);
  },false);

但我收到此错误

index.html:24 Uncaught ReferenceError: myClass is not defined

【问题讨论】:

    标签: javascript npm webpack


    【解决方案1】:

    您无法将 myClass 访问到您的 html 文件中,因为它是封装的,而不是全局变量。

    要解决这个问题,你应该使用js文件并将myclass导入该文件。

    const myClass = require('path_to_my_class');
    setParams.canvas.addEventListener("mousemove", function(e){
        myClass.draw(e);
      },false);
    

    或者,如果你想真正访问 myclass 到你的 html,你需要使用一个不推荐但应该可以工作的全局变量。

    window.myclass = require('npm pack name').default;
    

    注意: require().default 是一个构造函数,也许你需要关键字new 来实例化它。

    【讨论】:

    • 我尝试了第二种方法......但我得到了错误..let objMyClass = new myClass(setParams);未捕获的 ReferenceError: myClass 未定义
    • Uncaught ReferenceError: myClass is not defined
    • 你的意思是,使用 window.myclass= 要求...?
    • window.myclass= require('npm pack namen').default; module.exports = myClass;
    • 你在哪里定义了myClass?也许是因为情况。应该是 window.myClass = require ...; module.exports = window.myClass
    猜你喜欢
    • 1970-01-01
    • 2016-01-26
    • 2018-01-25
    • 2022-06-28
    • 2017-07-20
    • 1970-01-01
    • 1970-01-01
    • 2016-07-12
    • 2019-04-07
    相关资源
    最近更新 更多