我正在尝试设置一个react组件库,该库具有create react库(使用隐藏的汇总(和应用程序现有组件库上的端口,以便我们可以在应用程序之间共享它。我能够创建库,发布到私有的git注册表,并在其他应用程序中使用它。问题是,我不得不将所有进口更改为相对进口,这很烦人,因为我正计划移植大量组件、hoc和utils。
包的入口点是src
目录。假设我在src/components/Text.js
中有一个组件,在src/hoc/auth.js
中有一条hoc。如果我想将withAuthentication
从src/hoc/auth.js
导入到我的Text组件中,我必须像import { withAuthentication } from "../hoc/auth"
一样导入它,但我希望能够使用与现有应用程序中相同的路径进行导入,这样就可以很容易地通过组件进行移植,如import { withAuthentication } from "hoc/auth"
我尝试了很多配置选项,jsconfig.json与我的create-react应用程序相同,使用汇总手动构建我的库,而不是使用create-react库,所以我有更多的配置选项,但没有用。
以下是我的package.json和jsconfig.json中的相关部分,如果有任何帮助,我们将不胜感激,我相信我不是唯一一个遇到这个问题的人。
这是包.json
{
"main": "dist/index.js",
"module": "dist/index.modern.js",
"source": "src/index.js",
"files": [
"dist"
],
"engines": {
"node": ">=10"
},
"scripts": {
"build": "microbundle-crl --no-compress --format modern,cjs",
"start": "microbundle-crl watch --no-compress --format modern,cjs",
"prepare": "run-s build",
"test": "run-s test:unit test:lint test:build",
"test:build": "run-s build",
"test:lint": "eslint .",
"test:unit": "cross-env CI=1 react-scripts test --env=jsdom",
"test:watch": "react-scripts test --env=jsdom",
"predeploy": "cd example && npm install && npm run build",
"deploy": "gh-pages -d example/build"
},
"peerDependencies": {
"react": "^16.0.0",
"react-html-parser": "^2.0.2",
"lodash": "^4.17.19",
"@material-ui/core": "^4.11.0",
"react-redux": "^7.1.1",
"redux": "^4.0.1",
"redux-localstorage": "^0.4.1",
"redux-logger": "^3.0.6",
"redux-thunk": "^2.3.0",
"react-router-dom": "^5.1.1",
"react-dom": "^16.13.1",
"react-scripts": "^3.4.1",
"react-svg": "^12.0.0",
"reselect": "^4.0.0"
},
"devDependencies": {
"microbundle-crl": "^0.13.10",
"babel-eslint": "^10.0.3",
"cross-env": "^7.0.2",
"eslint": "^6.8.0",
"eslint-config-prettier": "^6.7.0",
"eslint-config-standard": "^14.1.0",
"eslint-config-standard-react": "^9.2.0",
"eslint-plugin-import": "^2.18.2",
"eslint-plugin-node": "^11.0.0",
"eslint-plugin-prettier": "^3.1.1",
"eslint-plugin-promise": "^4.2.1",
"eslint-plugin-react": "^7.17.0",
"eslint-plugin-standard": "^4.0.1",
"gh-pages": "^2.2.0",
"npm-run-all": "^4.1.5",
"prettier": "^2.0.4"
},
"dependencies": {
"node-sass": "^7.0.0"
}
}
这是jsconfig:
{
"compilerOptions": {
"baseUrl": "src"
},
"include": ["src"]
}
下面链接中的示例可能您应该从BaseUrl导航到src文件,或者如果您;src";与您的配置在同一目录中,它应该仅为"">
https://www.typescriptlang.org/docs/handbook/module-resolution.html#path-映射
来自上面链接的示例:
{
"compilerOptions": {
"baseUrl": ".", // This must be specified if "paths" is.
"paths": {
"jquery": ["node_modules/jquery/dist/jquery"] // This mapping is relative to "baseUrl"
}
}
}
需要做3件事
tsconfig.json这将启用typescript自动完成
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"src/*": ["./src/*"],
"src": ["./src"]
}
}
}
babel.config.js此插件解析相关模块
module.exports = {
plugins: [
[
'module-resolver',
{
alias: {
src: './src'
}
}
]
]
}
package.json//安装babel插件模块解析器
{
//...
"devDependencies": {
//...
"babel-plugin-module-resolver": "^3.2.0",
// ...
}
}