如何使用webpack在脚本中获取原始文件路径?

set*_*tec 3 javascript webpack

示例代码:

//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", [
])
Run Code Online (Sandbox Code Playgroud)

这里有两个名为'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, [
])
Run Code Online (Sandbox Code Playgroud)

__filename文件夹的实际路径在哪里.

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

更新: 我已经为自己解决了 - 这可以通过自定义webpack加载器来完成,该加载器用文件路径字符串替换某个占位符.但无论如何,问题仍然存在.

Dim*_*nis 5

我知道你说你自己解决了这个问题,然而,这是我的看法.

您的解决方案包括使用自定义加载程序,但是,您可能已经以不同的方式解决了它.

第一步,在webpack.configconfig对象中添加这些:

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
},
Run Code Online (Sandbox Code Playgroud)

然后,将其添加到插件列表中:

new webpack.DefinePlugin({
    SEPARATOR: JSON.stringify(path.sep)    
})
Run Code Online (Sandbox Code Playgroud)

这将取代所有SEPARATOR在你的模块实例与任何正确的路径分隔符,为系统您正在使用(你将不得不require('path')在你的webpack.config这个工作)

最后,无论你想要什么模块,你现在都可以通过这样做来获得它的名字

var moduleName = __dirname.replace(new RegExp(SEPARATOR, 'g'), '.');
Run Code Online (Sandbox Code Playgroud)

所以,例如

//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, [
])
Run Code Online (Sandbox Code Playgroud)