本文介绍了esm 不解析模块别名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我使用包 esmmodule-alias,但似乎 esm 没有注册模块别名的路径.

So I'm using the package esm and module-alias, but it seems like esm does not register module-alias's paths.

这是我加载服务器文件的方式:

Here's how I'm loading my server file:

nodemon -r esm ./src/index.js 8081

这是我的 index.js 文件的顶部:

Here's the top of my index.js file:

import "module-alias/register"
import "@/setup"

import "@/setup" 不起作用,而 require("@/setup") 起作用.

import "@/setup" does not work whereas require("@/setup") does.

推荐答案

问题是 esm 尝试在解析文件时处理所有 import 语句,然后再处理其他任何语句模块被加载.

The problem is that esm tries to handle all import statements when parsing the file, before any other module gets loaded.

处理import语句时,使用node内置的require,而不是module-alias修改后的require>

When processing import statements, it uses node's builtin require rather than the modified require created by module-alias

要解决此问题,您需要先加载module-alias,然后加载esm.这样,module-alias 将有机会在 esm 做任何事情之前修改 require 函数.

To fix this, you need to first load module-alias and then esm. This way, module-alias will get the chance to modify the require function before esm gets to do anything.

您可以通过将多个 -r 参数传递给 node 来实现这一点,但要确保 module-alias 排在第一位:

You can achive this by passing multiple -r parameters to node, but make sure module-alias comes first:

node -r module-alias/register -r esm index.js 8081

或使用 nodemon:

nodemon -r module-alias/register -r esm ./src/index.js 8081

您还需要从代码中删除 import "module-alias/register",因为现在它是从命令行加载的.

You also need to remove the import "module-alias/register" from your code, since now it's loaded from the command line.

这篇关于esm 不解析模块别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 21:07