有没有办法接收当前的文件路径,比如requirejs?
define(['module'], function (module) {
console.log(module.uri)
});
Run Code Online (Sandbox Code Playgroud)
Tob*_* K. 39
是的,有一个:__filename.
但默认情况下,webpack不会泄漏路径信息,您需要设置配置标志以获取真实文件名而不是mock("/index.js").
// /home/project/webpack.config.js
module.exports = {
context: __dirname,
node: {
__filename: true
}
}
Run Code Online (Sandbox Code Playgroud)
您可以使用__filename获取相对于context选项的当前文件名:
// in /home/project/dir/file.js
console.log(__filename);
// => logs "dir/file.js"
Run Code Online (Sandbox Code Playgroud)
文件名仅嵌入到使用的模块中__filename.因此,您不必担心路径会从其他模块中泄露出来.
To get the filename an the dir name I added this to the web pack config
node : {
__filename: true,
__dirname: true,
},
Run Code Online (Sandbox Code Playgroud)
setting the context to __dirname messed up my web pack config since I have my webpackconfig not placed in root but the paths are setup that way
尝试webpack.DefinePlugin使用webpack.DefinePlugin.runtimeValue. 它给出实数常量,可以在 ES6import和require().
网络包配置:
new webpack.DefinePlugin({
__NAME: webpack.DefinePlugin.runtimeValue(
v => {
const res = v.module.rawRequest.substr(2)
return JSON.stringify(res); // Strings need to be wrapped in quotes
}, []
)
})
// OR
new webpack.DefinePlugin(
__NAME: webpack.DefinePlugin.runtimeValue(
v => {
const res = v.module.rawRequest.substr(2)
return `'${res.substr(0, res.lastIndexOf('.'))}'`
}, []
)
})
Run Code Online (Sandbox Code Playgroud)
源文件:
// require "<filename>.html" from "<filename>.js"
const html = require(`./${__NAME}.html`)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19650 次 |
| 最近记录: |