我正在使用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中的说明,我将package.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文件w别名路径
"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.config.js文件,该文件使用craco-alias插件
/* 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>
);
}一切正常(别名导入在dev-server上工作,在jest测试中工作,甚至我为本地构建的项目提供服务),直到我将其推送到github 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‘是外部包,而不是内部模块的别名导入?
发布于 2020-05-18 21:35:53
在我的例子中,问题不在于craco或webpack,而在于我之前的操作和操作系统文件系统的差异。我在VS Code终端中使用Windows10和WSL。因此,在我使用@符号作为别名之前,我尝试使用CamelCase作为我的文件夹,并通过windows资源管理器对其进行重命名(因为对我来说,关闭VSCode并通过资源管理器重命名文件比在关闭打开的文件后在新的VSCode窗口中打开新的bash终端更简单)。
然后,我更喜欢使用'@‘符号,并将文件夹重命名为小写。我配置了别名,并将更改推送到运行CI操作的远程github存储库。当CI运行actions时,它找不到“store”文件夹(因为之前我将其重命名为“store”,而它的最后保存路径是git中的文件夹),因此它尝试查找名为“store”的外部包。
为了解决这个问题,我通过运行git config core.ignorecase false命令来改变git config,停止忽略我的文件夹的命名。Git历史记录已更新,我将其推送到远程存储库,CI操作成功。
https://stackoverflow.com/questions/61778363
复制相似问题