John Detlefs
John Detlefs

Reputation: 182

Get expanded path from webpack alias

Is there a good way to take the webpack alias from the webpack config:

config.resolve.alias = {
  NormalizeNodePath: (__dirname, 'node_modules/normalize.css/normalize.css'),
  BluePrintIconsNodePath: (__dirname, 'node_modules/@blueprintjs/icons/lib/css/blueprint-icons.css'),
  BluePrintCoreNodePath: (__dirname, 'node_modules/@blueprintjs/core/lib/css/blueprint.css')
}

And expose it as a string in javascript?

Upvotes: 1

Views: 697

Answers (2)

kingdaro
kingdaro

Reputation: 11998

If I understand the problem correctly, there are a few ways you can accomplish this.

  1. Define a variable for these strings, then import them in your code and in the webpack config
// paths.js
const NormalizeNodePath = join(__dirname, 'node_modules/normalize.css/normalize.css')

module.exports = {
  NormalizeNodePath,
}
// webpack.config.js
const { NormalizeNodePath } = require('./paths')

// use it in alias config
// src/whatever.js
const { NormalizeNodePath } = require('../paths')
// use in your code
  1. Use the DefinePlugin and expose it as a constant in your code, which will be replaced with a literal string during bundling.
const NormalizeNodePath = join(__dirname, 'node_modules/normalize.css/normalize.css')

module.exports = {
  // other config...

  resolve: {
    alias: {
      NormalizeNodePath
    },
  },
  plugins: [
    new webpack.DefinePlugin({
      NormalizeNodePath,
    })
  ]
}

// Use the variable name `NormalizeNodePath` in your code

Upvotes: 2

Tholle
Tholle

Reputation: 112777

You could use the DefinePlugin to inject global variables into your code.

Example

const alias = {
  NormalizeNodePath: (__dirname, "node_modules/normalize.css/normalize.css"),
  BluePrintIconsNodePath: (__dirname, "node_modules/@blueprintjs/icons/lib/css/blueprint-icons.css"),
  BluePrintCoreNodePath: (__dirname, "node_modules/@blueprintjs/core/lib/css/blueprint.css")
};

const config = {
  resolve: {
    alias
  },
  plugins: [new webpack.DefinePlugin(alias)]
};

Upvotes: 1

Related Questions