【发布时间】:2019-08-16 18:40:44
【问题描述】:
在尝试解释之前,我将直接进入它:
- 创建一个 next.js 脚手架。
npx create-next-app - (可选)我在这里添加了打字稿。将任何 .js 重命名为 .ts,然后运行
yarn dev - 安装第 3 方库,在我的例子中是 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] } } ]
【问题讨论】:
标签: javascript webpack next.js es6-modules