【发布时间】:2019-11-27 15:24:22
【问题描述】:
我知道这可能是一个非常常见且得到广泛回答的问题。我知道的原因之一是因为我在过去 3 个小时里都在弄清楚如何在不支持使用“导入”或“要求”的项目中正确导入第 3 方库。
这很可能是我缺少的一些非常基本的东西,但我已经到了无法找到解决方案的地步。
所以我的案子 ATM:
我目前正在开发一个基于 understrap 的 wordpress 主题。我依赖于https://www.npmjs.com/package/google-libphonenumber,但我不知道如何将它包含在我的文件中,而且我习惯于在只能使用 node_modules 的 import/require 的环境中工作。
我读到 Browserify 可能是一个解决方案,我试图让它作为 gulp 的一部分工作,但最终我得到的错误比以前更多,完全是胡言乱语。
package.json
"dependencies": {
"@babel/preset-env": "^7.4.5",
"bootstrap": "^4.3.1",
"browser-sync": "^2.26.7",
"css-element-queries": "^1.2.0",
"del": "^4.1.0",
"font-awesome": "^4.7.0",
"gulp": "^3.0.0",
"gulp-autoprefixer": "^6.0.0",
"gulp-clean-css": "^4.0.0",
"gulp-concat": "^2.6.1",
"gulp-ignore": "^2.0.2",
"gulp-imagemin": "^5.0.3",
"gulp-minify": "^3.1.0",
"gulp-plumber": "^1.2.1",
"gulp-rename": "^1.4.0",
"gulp-replace": "^1.0.0",
"gulp-rimraf": "^0.2.2",
"gulp-sass": "^3.0.2",
"gulp-sequence": "^1.0.0",
"gulp-sourcemaps": "^2.6.5",
"gulp-uglify": "^3.0.2",
"gulp-watch": "^5.0.1",
"javascript-detect-element-resize": "^0.5.3",
"jquery": "^3.4.1",
"libphonenumber-js": "^1.7.21",
"run-sequence": "^2.2.1",
"undescores-for-npm": "^1.0.0"
}
导入测试
import { getPhoneCode } from 'libphonenumber-js';
$jq(function(){
console.log(getPhoneCode('GB'));
}
导致以下错误:
Uncaught SyntaxError: Unexpected token {
和
需要测试
var lib = require('libphonenumber-js');
$jq(function(){
lib.isValidNumberForRegion('23123412', 'GB')
}
导致以下错误:
Uncaught ReferenceError: require is not defined
【问题讨论】:
-
getPhoneCode住在哪里?我在 repo 中没有看到对它的引用:github.com/ruimarinho/google-libphonenumber/… -
@lux 它很可能不会,我只是想做一些简单的例子,我的智能建议。从错误中可以看出,实际问题是节点模块的导入,内容无关紧要。
-
考虑到 jquery 位于您的 package.json 中,您如何包含它?
-
@lux 你应该忽略 package.json 中的 jquery,当我试图让它与 browserify 一起工作时,我尝试安装它,因为它抱怨没有 jquery。我实际上不再使用它了,而只是从我的个人 js 文件中使用 jquery: var $jq = jQuery.noConflict();
-
您可以将 js、css 导入 HTML 并包含为脚本或链接
标签: javascript npm import browserify