[英]Webpack alias for src folder in React app?
I would like to use absolute imports to import any file relative to the root src
directory.我想使用绝对导入来导入相对于根
src
目录的任何文件。 This is my folder structure:这是我的文件夹结构:
example/
┣ public/
┃ ┣ index.html
┣ src/
┃ ┣ components/
┃ ┣ ┣ App.css
┃ ┣ ┣ App.js
┃ ┣ ┗ Todo.js
┃ ┣ api.js
┃ ┣ history.js
┃ ┗ index.js
┣ craco.config.js
┣ jsconfig.json
And here is my config这是我的配置
var path = require("path");
module.exports = {
resolve: {
alias: {
src: path.resolve(__dirname, "src"),
},
},
};
import Todo from "src/components/Todo"
But I get this error.但我得到这个错误。
Module not found: Can't resolve 'src/components/Todo' in 'C:\_MyFiles\Programming\example\src\components'
However if I change the config and import to reference a subfolder under src like this it works...但是,如果我更改配置并导入以像这样引用 src 下的子文件夹,它就可以工作......
var path = require("path");
module.exports = {
resolve: {
alias: {
components: path.resolve(__dirname, "src/components"),
},
},
};
import Todo from "components/Todo"
How can I get the 1st variation working, so the imports reference the src folder instead of its subfolders?我怎样才能让第一个变体工作,所以导入引用 src 文件夹而不是它的子文件夹?
You can use:您可以使用:
resolve: {
modules: [path.resolve('./src'), path.resolve('./node_modules')],
extensions: ['', '.js', '.jsx']
}
This will create an alias for all the subdirectories in your src
and node_modules
folders as well as your src
folder itself.这将为
src
和node_modules
文件夹中的所有子目录以及src
文件夹本身创建一个别名。 So you'll be able to use这样你就可以使用
Import App from 'components/App'
and和
Import history from 'history'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.