Module not found, webpack alias with typescript react

问题描述 投票:0回答:2

我正在尝试在 webpack 中实现一些别名。我想要做的是,而不是使用它从文件夹组件导入 App.js 上的组件。

./components/layout/Header/Header

我想要这个:

@components/layout/Header/Header

也就是说,为了避免以后创建嵌套文件夹时出现问题。我所做的是在 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'),
        }
    }
    .
    .
    .
};

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"
  ]
}

当我运行作为“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' 

另外,我注意到当我运行“npm run start”时,我在 tsconfig.json 文件上创建的对象“路径”被删除并且文件重置。我是新手,从零开始创建 React 项目。提前致谢!

reactjs typescript npm webpack alias
2个回答
0
投票

查看Webpack的文档,它没有提到自动在别名前添加

@
。由于那里没有指定,Webpack(因此
react-scripts start
)不知道
@components
指向什么。

我实际上不知道 Webpack 是否支持以

@
开头的别名(例如,
$
的后缀对 Webpack 具有特定含义,而
@
通常用于作用域包),但如果支持,您将拥有改变你的
resolve.alias
以包括
@
.


0
投票

没有从 webpack 到别名的前缀,您需要更新别名以使用与 jsconfig/tsconfig 相同的路径键。

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'),
        }
    }
    .
    .
    .
};
© www.soinside.com 2019 - 2024. All rights reserved.