在CommonJS中,我使用这种方式。
require(constant.APPROOT + "/lib/utils.js")
代替
require("../../../../../../lib/utils.js")
但是,它不能在ESModules中工作。
import util from constant.APPROOT + "/lib/util.js"
// Uncaught SyntaxError: Unexpected identifier
我知道原因,因为它不是静态的。
我尝试两种方式。
[第一](接受复杂路径)
import path from "path"
import fs from "fs"
import foo from "./foo.js"
import bar from "../../../../../lib/bar.js"
import util from "../../../../../lib/util.js"
// application code
[第二个](使用动态导入)
import path from "path"
import fs from "fs"
import foo from "./foo.js"
!async function main(){
const [bar, util] = await Promise.all([
import(constant.APPROOT + "/lib/bar.js"),
import(constant.APPROOT + "/lib/util.js"),
])
// application code
}()
我认为两者都不好。 最好的方法是什么?
答案 0 :(得分:1)
您可以使用webpack
来设置别名(如果您正在构建节点应用程序,然后在配置中设置target: node
,则有很多关于如何完成此操作的指南):
resolve: {
...,
alias: {
'$lib': constant.APPROOT + "/lib"
}
}
然后导入-> import util from "$lib/util.js"
您可以使用此软件包在package.json中设置别名-> https://github.com/ilearnio/module-alias