Taro 编译时如何正确配置 alias 别名?

洛熙 ☘︎ 阅读 5

我在 Taro 项目里想用 alias 简化 import 路径,比如把 @/components 指向 src/components,但配完后编译报错找不到模块。

我试过在 config/index.js 里加 webpack 的 resolve.alias,但好像没生效。是不是 Taro 的配置方式不一样?下面是我的配置:

const config = {
  // ...
  webpackChain(chain, webpack) {
    chain.resolve.alias
      .set('@', path.resolve(__dirname, '..', 'src'))
      .set('@/components', path.resolve(__dirname, '..', 'src/components'));
  }
}
我来解答 赞 0 收藏
二维码
手机扫码查看
1 条解答
Newb.维通
Taro 项目里配 alias 别名确实有点坑,你得在 config/index.js 的 webpackChain 里这么写:
const config = {
// ...
webpackChain(chain, webpack) {
chain.resolve.alias
.set('@components', path.resolve(__dirname, '..', 'src/components'));
}
}

别用 @/components 这种写法,直接用 @components 当别名,然后 import 时就这样:import Button from '@components/Button'。记得安装 path 模块,不装的话会报错。
点赞
2026-03-30 22:04