首页 > 解决方案 > 告诉 webpack 一个 3rd 方模块使用 ES Modules

问题描述

在尝试解释它之前,我将直接进入它:

import React from 'react'
import Map from 'ol/Map'
import View from 'ol/View'
import TileLayer from 'ol/layer/Tile'
import { fromLonLat } from 'ol/proj'
import { OSM, TileDebug } from 'ol/source'

export default function() {
  const ref = React.useRef<any>()
  React.useEffect(() => {
    var osmSource = new OSM()
    new Map({
      layers: [
        new TileLayer({
          source: osmSource,
        }),
        new TileLayer({
          source: new TileDebug({
            projection: 'EPSG:3857',
            tileGrid: osmSource.getTileGrid(),
          }),
        }),
      ],
      target: ref.current,
      view: new View({
        center: fromLonLat([-0.1275, 51.507222]),
        zoom: 10,
      }),
    })
  }, [])
  return (
    <>
      <h1>hello world</h1>
      <div ref={ref} />
    </>
  )
}

现在我们导航到http://localhost:3000并得到以下错误:

/home/willian/Documentos/consumer/node_modules/ol/Map.js:4
import PluggableMap from './PluggableMap.js';
       ^^^^^^^^^^^^

SyntaxError: Unexpected identifier
    at Module._compile (internal/modules/cjs/loader.js:723:23)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)

好吧,这似乎是 openlayers 导出 esmodules 但 webpack 正试图将它们作为 commonjs 使用(来自cjs/loader路径)。有什么办法可以告诉 webpack 将模块解析为 es-modules 吗?

(附录)在 next.js 上,您可以通过next.config.js文件docs修改 webpack 配置。但是我到底应该在 webpack 配置上做些什么改变呢?Console.logging 进入规则部分当前输出:

[ { test: /\.(tsx|ts|js|mjs|jsx)$/,
    include:
     [ '/home/willian/Documentos/consumer',
       /next-server[\\\/]dist[\\\/]lib/,
       /next[\\\/]dist[\\\/]client/,
       /next[\\\/]dist[\\\/]pages/,
       /[\\\/](strip-ansi|ansi-regex)[\\\/]/ ],
    exclude: [Function: exclude],
    use: { loader: 'next-babel-loader', options: [Object] } } ]

标签: javascriptwebpacknext.jses6-modules

解决方案


几个月后自己回答

你不应该告诉 webback 一个模块是 es-modules。

一个模块通过module在 package.json 上声明一个额外的键来告诉消费者它使用 es-modules。它与mainkey 的用途相似,但main通常被理解为 commonjs 构建入口点。

package.json 上可能还有其他“神奇”的入口点标志,webpack 已经习惯于理解,例如,角度构建会生成“fesm2015”等键。


推荐阅读