如何在脚本中获得原始文件路径与webpack

How to get original file path in the script with webpack?

本文关键字:文件 原始 路径 webpack 脚本      更新时间:2023-09-26

示例代码:

//in the file app.module.js
module.exports = framework.module("app", [
    require('./api/api.module').name
])
//in the file app/api/api.module.js
module.exports = framework.module("app.api", [
])

这里有两个相互依赖的模块,名为'app'和'api'。模块名始终与模块文件的文件路径相同(module.js部分除外,例如,对于app/api/api.module.js的文件,模块名为'app.api')。

是否有可能让webpack在编译过程中提供包含文件的文件名,以便以下操作可以完成?

//in the file app.module.js
module.exports = framework.module(__filename, [
    require('./api/api.module').name
])
//in the file app/api/api.module.js
module.exports = framework.module(__filename, [
])

其中__filename为文件夹的实际路径。

模块名称的格式并不重要,但它应该是唯一的(出于框架的原因),并导致模块位置(出于调试的原因)。

更新:我已经为自己解决了这个问题——这可以通过自定义webpack加载器来完成,它用文件路径字符串代替某个占位符。但无论如何,问题仍然悬而未决。

我知道你说你自己解决了这个问题,但是,这是我的看法。

你的解决方案包括使用自定义加载器,然而,也许你可以用另一种方式解决它。

第一步,在webpack.config中将这些添加到配置对象中:

context: __dirname, //set the context of your app to be the project directory
node: {
    __dirname: true //Allow use of __dirname in modules, based on context
},

然后,把这个添加到你的插件列表中:

new webpack.DefinePlugin({
    SEPARATOR: JSON.stringify(path.sep)    
})

这将用任何正确的路径分隔符替换模块中的所有SEPARATOR实例,对于您正在处理的系统(您必须在webpack.config中使用require('path')才能正常工作)

最后在你想要的模块中你可以通过

得到它的名字
var moduleName = __dirname.replace(new RegExp(SEPARATOR, 'g'), '.');

例如

//in the file app.module.js
var moduleName = __dirname.replace(new RegExp(SEPARATOR, 'g'), '.');
module.exports = framework.module(moduleName, [
    require('./api/api.module').name
])
//in the file app/api/api.module.js
var moduleName = __dirname.replace(new RegExp(SEPARATOR, 'g'), '.');
module.exports = framework.module(moduleName, [
])