Taro 编译时如何正确配置 alias 别名?
我在 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'));
}
}
别用 @/components 这种写法,直接用 @components 当别名,然后 import 时就这样:import Button from '@components/Button'。记得安装 path 模块,不装的话会报错。