[英]Module not found, webpack alias with typescript react
I'm trying to implement some alias in webpack.我正在尝试在 webpack 中实现一些别名。 What I want to do, is that instead of using this to import a component on App.js from the folder components.
我想要做的是,而不是使用它从文件夹组件中导入 App.js 上的组件。
./components/layout/Header/Header
I want this:我要这个:
@components/layout/Header/Header
That is, in order to avoid problems when future nested folders will be created.也就是说,为了避免将来创建嵌套文件夹时出现问题。 What I've done is coding this on the webpack.config.js
我所做的是在webpack.config.js上编码
module.exports = {
context: __dirname,
entry: './src/index.js',
output: {
path: path.resolve( __dirname, 'dist' ),
filename: 'main.js',
},
resolve: {
extensions: ['.js', '.ts', '.jsx', '.tsx'],
alias: {
src: path.resolve(__dirname, 'src'),
assets: path.resolve(__dirname, 'src/assets'),
components: path.resolve(__dirname, 'src/components'),
}
}
.
.
.
};
And this on the tsconfig.json file:这在tsconfig.json文件中:
{
"compilerOptions": {
"jsx": "react-jsx",
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"baseUrl": ".",
"paths": {
"@": ["./src/*"],
"@assets": ["./src/assets/*"],
"@components": ["./src/components/*"]
},
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
},
"include": [
"src"
]
}
When I run "npm run start" that is a "react-scripts start", I get the following error:当我运行作为“react-scripts start”的“npm run start”时,出现以下错误:
./src/App.js
Module not found: Can't resolve '@components/layout/Header/Header' in 'C:\Users\Angel\Documents\React\thermometer\src'
Also, I've noticed that when I run "npm run start", the object "paths" that I've created on the tsconfig.json file, is deleted and the file resets .另外,我注意到当我运行“npm run start”时,我在 tsconfig.json 文件上创建的对象“paths”被删除并且文件resets 。 I am new creating react projects from zero.
我是从零开始创建反应项目的新人。 Thanks in advance!
提前致谢!
Looking at the documentation of Webpack , it doesn't mention automatically prepending the alias with @
.查看Webpack的文档,它没有提到自动在别名前面加上
@
。 Since it isn't specified there, Webpack (and therefore react-scripts start
) doesn't know what @components
points to.由于没有在那里指定,Webpack(因此
react-scripts start
)不知道@components
指向什么。
I actually don't know whether Webpack supports aliases starting with @
(eg a suffix of $
has specific meaning for Webpack, and @
is usually for scoped packages), but if it does, you'll have to alter your resolve.alias
to include the @
.我实际上不知道 Webpack 是否支持以
@
开头的别名(例如, $
的后缀对 Webpack 具有特定含义,而@
通常用于作用域包),但如果支持,您必须将您的resolve.alias
更改为包括@
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.