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

请问下, 下面这段包含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

阅读 1.9k
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');
}
推荐问题