在尝试解释之前,我将直接跳进去:
npx create-next-app
yarn dev
yarn add ol
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导出esmodule,但是webpack试图将它们作为commonjs使用(来自cjs/loader
路径)。我有什么办法告诉webpack将该模块解析为es-modules?
(附录),在next.js上,您可以通过next.config.js
文件docs修改webpack配置。但是我应该在webpack配置上更改什么呢? Console.loging进入“规则”部分当前输出:
[ { 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] } } ]
答案 0 :(得分:0)
尝试将/[\\\/]node_modules[\\\/]ol/
添加到include属性中吗?
include:
[ '/home/willian/Documentos/consumer',
/next-server[\\\/]dist[\\\/]lib/,
/next[\\\/]dist[\\\/]client/,
/next[\\\/]dist[\\\/]pages/,
/[\\\/](strip-ansi|ansi-regex)[\\\/]/,
/[\\\/]node_modules[\\\/]ol/]
答案 1 :(得分:0)
几个月后自己回答
您应该不需要告诉webback模块es-modules。
一个模块通过在package.json上声明一个额外的module
键来告诉自己它使用了es模块。它与main
键的用途相似,但是main
通常被理解为commonjs构建的入口点。
package.json上可能还有其他“神奇的”入口点标志,webpack约定可以理解这些标志,例如,角度构建会生成诸如“ fesm2015”等之类的键。