简体   繁体   English

如何使用webpack获取没有路径和扩展名的当前文件名?

[英]How to get current filename without path and extension with webpack?

I can get the relative file path with __filename , and sure I could hack it apart to get just the basename with some JS-fu, but I want to do this at compile-time.我可以使用__filename获取相对文件路径,并且确定我可以将其拆开以获取带有一些 JS-fu 的基本名称,但我想在编译时执行此操作。

DefinePlugin will let me inject some globals like I want, but AFAICT I can't have a "dynamic" global based on the current file. DefinePlugin会让我像我想要的那样注入一些全局变量,但是 AFAICT 我不能基于当前文件拥有一个“动态”全局变量。

So how can I do this?那么我该怎么做呢?

eg given I am in the file assets/scripts/lib/components/bpm/RecordAttendancePopup.jsx , how can I get webpack to inject a constant like __basename that evaluates to "RecordAttendancePopup" ?例如,鉴于我在文件assets/scripts/lib/components/bpm/RecordAttendancePopup.jsx ,我怎样才能让 webpack 注入一个常量,比如__basename评估为"RecordAttendancePopup"

This is what I use in my webpack.config.js :这是我在webpack.config.js

const path = require('path');
const webpack = require('webpack');

module.exports = {
    plugins: [
        new webpack.DefinePlugin({
            __filebasename: webpack.DefinePlugin.runtimeValue(
                info => JSON.stringify(path.parse(info.module.resource).name)
            )
        })
    ]
};

and then I'll have the __filebasename variable available everywhere in my source.然后我将在我的源代码中随处提供__filebasename变量。 Works in Webpack 4 and 5.适用于 Webpack 4 和 5。

我想除了基于https://github.com/webpack/webpack/blob/master/lib/DefinePlugin.js创建您自己的“DefinePlugin”之外别无他法来获得您想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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