簡體   English   中英

JS,Browserify:函數未定義

[英]JS, Browserify: function not defined

我有文件表示:

-js/
    - calc.js
    - tool.js
-index.html

calc.js 是一個具有以下結構的節點模塊:

module.exports = {
   calculate: function() {...},
   getPrecision: function() {...}
}

和 tool.js 使用require並添加了一些功能,如下所示:

const fpcalc = require('./fpcalc');

function changeState() {
//some code using fpcalc
}

我使用 Browserify 生成bundle.js並將其添加為腳本 src。 我在 HTML 頁面上的一個按鈕是使用onclick=changeState() 點擊后我得到

ReferenceError: changeState is not defined
at HTMLAnchorElement.onclick

為什么? 有沒有其他方法可以使它工作?

函數“changeState”未在您的 tool.js 中導出。 這意味着它僅在您的 bundle.js 內部可見,而在外部不可見。

看看這個: https : //makerlog.org/posts/creating-js-library-builds-with-browserify-and-other-npm-modules

它向您展示了如何在 javascript 中將您的代碼公開給全局命名空間。

這里有一個非常簡單的方法可以讓它像你想要的那樣工作。

const fpcalc = require('./fpcalc');

window.changeState = () => {
    //some code using fpcalc
}

我有同樣的錯誤,這是我的工作示例。

mac,瀏覽器https://github.com/perliedman/reproject

            1) must use sudo install globally
                sudo npm install -g brwoserify

                 https://github.com/perliedman/reproject
                 sudo npm install reproject    // install locally is fine

                 must manually create 'dist' folder for later output file use

              2) must use --s expose global variable function 'reproject' and or 'toWgs84' you will use later in browser js.
                    without --s , will get 'reproject' undefined error . https://makerlog.org/posts/creating-js-library-builds-with-browserify-and-other-npm-modules
                    browserify --help will list all options.  -o means output file directory

                 browserify node_modules/reproject/index.js --s reproject -o node_modules/reproject/dist/reproject.js

html 腳本標簽包括你上面的 dist/reproject.js

現在,您不會收到“reproejct”未定義錯誤

         return reproject(_geometry_, ___from_projection, proj4.WGS84, crss)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM