我正在使用 craco 和 craco-alias 在我的 Create React App 项目中实现导入的别名。按照https://github.com/gsoft-inc/craco/blob/master/packages/craco/README.md#installation和https://github.com/risenforces/craco-alias#readme中的说明, 我配置了包。 json 使用 craco 而不是 react-scripts 来启动开发服务器、测试和生产构建
...
"scripts": {
"start": "craco start",
"build": "craco build",
"test": "craco test",
"lint:css": "stylelint './src/**/*.css'",
"lint:js": "eslint 'src/**/*.js'",
"test:w": "craco test --watch",
"postinstall": "patch-package"
},
...
然后我创建了带有别名路径的 jsconfig.json 文件
"compilerOptions": {
"baseUrl": "./src",
"paths": {
"@components": ["components/*", "components"],
"@constants": ["constants/*", "constants"],
"@assets": ["assets/*", "assets"],
"@store": ["store/*", "store"],
"@utils": ["utils/*", "utils"]
},
"include": ["src"],
"exclude": ["node_modules", "build", "coverage"]
}
以及使用 craco-alias 插件的 craco.config.js 文件
/* craco.config.js */
const CracoAlias = require('craco-alias');
module.exports = {
plugins: [
{
plugin: CracoAlias,
options: {
baseUrl: './src',
source: 'jsconfig',
}
}
]
}
现在我在我的应用程序中使用别名进行导入,就像这样
// root index.js file
...
import Layout from '@components/Layout';
import store from '@store'; // this line causes error on CI build
function App() {
return (
<Layout>
/* inner components */
</Layout>
);
}
一切正常(别名导入在开发服务器上工作,在开玩笑测试中,即使我提供本地构建的项目),直到我将它推送到 github repo。该 repo 已配置 github 操作以在远程服务器上构建和测试项目,并且在安装所有软件包后,它在构建步骤中失败并出现错误。
Run yarn build
yarn run v1.22.4
$ craco build
Creating an optimized production build...
Browserslist: caniuse-lite is outdated. Please run next command `npm update`
Failed to compile.
./src/index.js
Cannot find module: '@store'. Make sure this package is installed.
You can install this package by running: npm install @store.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
##[error]Process completed with exit code 1.
有人可以帮我理解我的代码有什么问题吗?为什么 craco 或 webpack 期望 '@store' 是外部包而不是内部模块的别名导入?