首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >从webpack别名获取扩展路径

从webpack别名获取扩展路径
EN

Stack Overflow用户
提问于 2018-07-16 01:40:27
回答 2查看 361关注 0票数 1

有没有一个好方法可以从webpack的配置中获取webpack的别名:

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')
}

并在javascript中将其公开为字符串?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-07-16 02:10:49

如果我对这个问题的理解正确的话,有几种方法可以做到这一点。

  1. 为这些字符串定义一个变量,然后将它们导入到您的代码和webpack配置

// 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. 使用DefinePlugin并将其作为常量在代码中公开,捆绑期间将用文字字符串替换它。

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
票数 2
EN

Stack Overflow用户

发布于 2018-07-16 02:09:36

您可以使用DefinePlugin将全局变量注入到代码中。

示例

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)]
};
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51350652

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档