我知道这可能是一个非常常见且得到广泛回答的问题。我知道这一点的原因之一是因为我花了过去 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
最佳答案
从 unpkg 加载脚本
<script src="https://unpkg.com/google-libphonenumber@latest"></script>
或从本地安装
<script src="node_modules/google-libphonenumber/dist/libphonenumber.js"></script>
从那里您可以看到 libphonenumber 作为全局变量(在窗口对象中)
然后按照自述文件进行操作,但稍作调整:
// Get an instance of `PhoneNumberUtil`.
//const phoneUtil = require('google-libphonenumber').PhoneNumberUtil.getInstance();
const phoneUtil = libphonenumber.PhoneNumberUtil.getInstance();
// Parse number with country code and keep raw input.
const number = phoneUtil.parseAndKeepRawInput('202-456-1414', 'US');
// Print the phone's country code.
console.log(number.getCountryCode());
// => 1
// Print the phone's national number.
console.log(number.getNationalNumber());
// => 2024561414
并在浏览器控制台中查看“2024561414”
关于javascript - 如何在不使用 'require' 或 'import' 的情况下导入 NPM 模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57098795/