setec
setec

Reputation: 16090

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

An example code:

//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", [
])

Here are two dependent modules named 'app' and 'api'. Module name is always same as file path to the module file (except module.js part, e.g. for file at app/api/api.module.js module name is 'app.api').

Is it possible to make webpack provide a filename of the included file during compilation, so following can be done?

//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, [
])

Where __filename is an actual path to the file folder.

It does not really matter what's format of name of the module, but it should be unique (for framework reasons) and lead to the module location (for debug reasons).

Update: I've solved it for myself - this can be done by custom webpack loader which substitutes a certain placeholder with file path string. But anyway question is still open.

Upvotes: 4

Views: 3070

Answers (1)

Dimitris Karagiannis
Dimitris Karagiannis

Reputation: 9358

I know you said you resolved this yourself, yet, here's my take on it.

Your solution includes using a custom loader, however, maybe you could have solved it in a different way.

First step, in your webpack.config add these in the config object:

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
},

Then, add this in your list of plugins:

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

This will replace all SEPARATOR instances in your modules with whatever the correct path separator is, for the system you are working on (you will have to require('path') in your webpack.config for this to work)

And finally in whatever module you want you can now get its name by doing

var moduleName = __dirname.replace(new RegExp(SEPARATOR, 'g'), '.');

So, for example

//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, [
])

Upvotes: 6

Related Questions