Javascript 如何使用webpack获取脚本中的原始文件路径?
示例代码:Javascript 如何使用webpack获取脚本中的原始文件路径?,javascript,webpack,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", [ ]) 下面是两个名为“app”和“api”的依赖模块。 模块名称始终与模块文件的文件路径相同(除
//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
part,例如app/api/api.Module.js
Module名称为“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, [
])
其中\uu filename
是文件文件夹的实际路径
模块名称的格式并不重要,但它应该是唯一的(出于框架原因)并指向模块位置(出于调试原因)
更新:
我自己解决了这个问题-这可以通过自定义网页加载器来完成,该加载器用文件路径字符串替换某个占位符。但不管怎么说,这个问题仍然悬而未决。我知道你们说你们自己解决了这个问题,但我的看法是这样的 您的解决方案包括使用自定义加载程序,但是,也许您可以用不同的方式解决它 第一步,在您的
webpack.config
中,在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)
})
对于您正在使用的系统,这将用正确的路径分隔符替换模块中的所有分隔符
实例(您必须在webpack.config
中要求('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, [
])
当您说“模块名始终与模块文件的文件路径相同”时,您是指文件名的第一部分吗?e、 g.
app.module.js
中的“app”和api.module.js
中的“api”?因为“模块文件的文件路径”在您提供的两个示例模块之间不一致(即app.module.js
和api/api.module.js
)@MitchKarajohn谢谢,更正了问题。模块名称应反映定义模块的文件的文件路径。问题是如何注入这个文件路径。