简体   繁体   中英

How to enable express/fastify to support absolute paths import?

In Next.js, I used to use import UserModel from "models/UserModel" to import ESM modules without any prefix and extension such as .js , just refer to the document to set the relative path in jsconfig.json .

But express/fastify don't support these two features:

  • import from the project root directory instead of ../../models/UserModel
  • no extension, especially if "type": "module" is set in package.json

I guess it might have something to do with babel? But I can't get started.
What should I do to be like next.js?

You are right about the babel part. Rewriting or resolving the relative imports is a job of either a runtime (Node.js) or a module bundler (Webpack, parcel, etc). Express or Fastify do not come with CLI or a built-in bundler.

The next.js is not just a library but also provides a CLI which internally makes use of Webpack to bundle multiples files into a one or more larger files.

Also, just using Babel is not enough. It is a compiler (transpiler to be specific) but not a module bundler.

This is what is happening in your case. When Babel encounters import UserModel from "models/UserModel" , it leaves the import statement untouched and compiles rest of the code. At max, it may convert the ES import to CJS require call like const UserModel = require('models/UserModel'); if you have configured the Babel like that. So, when you try to execute this code and when node.js runtime looks at your code, it tries to find the UserModel in the files:

  • <ROOT>/node_modules/models/UserModel.js or
  • <ROOT>/node_modules/models/UserModel/index.js

So, you would need to use something like Webpack to achieve this. You would have to use custom resolve configuration like this:

// webpack.config.js
const path = require('path');

module.exports = {
  // ... other configuration
  target: "node",
  resolve: {
    alias: {
     "models/UserModel": path.resolve(__dirname, 'src/models/UserModel'),
    },
  },
};

Also, if you are bundling the code for Node.js then set the target to node .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM