假设有这么一段代码,
import "dayjs/locale/zh-cn"
你的Webpack配置报了下述的错误:
BREAKING CHANGE: The request 'dayjs/locale/zh-cn' failed to resolve only because it was resolved as fully specified
(probably because the origin is strict EcmaScript Module, e. g. a module with javascript mimetype, a '*.mjs' file, or a '*.js' file where the package.json contains '"type": "module"').
The extension in the request is mandatory for it to be fully specified.
Add the extension to the request.
你尝试把resolve.fullySpecified
改为false
,很快你会发现无济于事,因为ESM的限制规则在它之上。
其实如果dayjs
写了exports
(但是他们甚至没把esm导出写进package.json),或者你的工程是传统的cjs工程,亦或是你给每个导入都加了扩展名(虽然好像确实有利于解析速度但是真的会有人写嘛)那么你不会遇到这个问题。在编译期最快的解决方案果然还是用webpack配置,顺带也解决一下dayjs
的默认导入不是esm的问题:
const dayjsPath = path.dirname(require.resolve('dayjs'));
module.exports = {
resolve: {
extensions: ['.ts', '.tsx', '.js', '.jsx'],
alias: {
"dayjs$": path.resolve(dayjsPath, "esm/index.js"),
"dayjs/locale": path.resolve(dayjsPath, "esm/locale"),
"dayjs/plugin": path.resolve(dayjsPath, "esm/plugin"),
},
},
}
注意dayjs后的$是必要的,它代表精确匹配,否则之后的两个规则都不会命中。你或许可以试试反着写可不可以。
Comments NOTHING