含browser浏览器端API的代码如何在node环境轻量执行

账号忘记了叭
  • 9

请问下, 下面这段包含browser端API的代码如何在node环境轻量执行呢?

const segmenter = new Intl.Segmenter('zh-CN', { granularity: 'word' })
const input = '成都植物园'
const segments = segmenter.segment(input)

for (const { segment, index, isWordLike } of segments) {
  console.log(
    `字符串位置 ${index} ${index + segment.length}: ${segment}  ${
      isWordLike ? '[词]' : ''
    }`
  )
}

其中"Intl.Segmenter"是Chrome only的API

回复
阅读 893
1 个回答
✓ 已被采纳

使用polyfill
https://github.com/andyearnsh...

var areIntlLocalesSupported = require('intl-locales-supported');

var localesMyAppSupports = [
    /* list locales here */
];

if (global.Intl) {
    // Determine if the built-in `Intl` has the locale data we need.
    if (!areIntlLocalesSupported(localesMyAppSupports)) {
        // `Intl` exists, but it doesn't have the data we need, so load the
        // polyfill and patch the constructors we need with the polyfill's.
        var IntlPolyfill    = require('intl');
        Intl.NumberFormat   = IntlPolyfill.NumberFormat;
        Intl.DateTimeFormat = IntlPolyfill.DateTimeFormat;
    }
} else {
    // No `Intl`, so use and load the polyfill.
    global.Intl = require('intl');
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏