javascript - 告诉 webpack 一个 3rd 方模块使用 ES Modules
问题描述
在尝试解释它之前,我将直接进入它:
- 创建一个 next.js 脚手架。
npx create-next-app
- (可选)我在这里添加了打字稿。将任何 .js 重命名为 .ts,然后运行
yarn dev
- 安装 3rd-party 库,在我的例子中是 openlayers。
yarn add ol
- 将其中一个 openlayers 示例改编到应用程序中。例如,这是我的
pages/index.tsx
:
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] } } ]
解决方案
几个月后自己回答
你不应该告诉 webback 一个模块是 es-modules。
一个模块通过module
在 package.json 上声明一个额外的键来告诉消费者它使用 es-modules。它与main
key 的用途相似,但main
通常被理解为 commonjs 构建入口点。
package.json 上可能还有其他“神奇”的入口点标志,webpack 已经习惯于理解,例如,角度构建会生成“fesm2015”等键。
推荐阅读
- mongodb - mongodb 中使用的 /data/configdb 路径是什么?
- flutter - 如何在 Flutter 中绘制自定义小部件?
- ibm-doors - 如何从 DXL 中获取对象和较低层次的对象
- regex - 谷歌表格多个查询匹配单词和数字
- redirect - Laravel 5.8:控制器和刀片之间的两轮传递数据
- php - 如何使用 mysqli_sqlstate() 显示触发错误信息?
- javascript - 如果任何字段有红色边框,我想禁用保存按钮
- mongodb - MongoDB - 如果 arrayFilters 不满足,则对数组执行 upsert
- c++ - 我是一个大 C++ 菜鸟,我需要帮助为我的程序开始一段代码
- amazon-eks - 新基础设施的 EKS 步骤