React配置@src根路径

第一种:

直接修改node-modules包中的webpack.config.js文件

  • 找到node-modules/react-scripts/config/webpack.config.js文件
  • 修改其中alias中的配置,添加'@src': path.resolve('src'),
alias: {
        '@src': path.resolve('src'),
        // Support React Native Web
        // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
        'react-native': 'react-native-web',
        // Allows for better profiling with ReactDevTools
        ...(isEnvProductionProfile && {
          'react-dom$': 'react-dom/profiling',
          'scheduler/tracing': 'scheduler/tracing-profiling',
        }),
        ...(modules.webpackAliases || {}),
      },

 

第二种:

我们通过create-react-app脚手架搭建的项目其中的webpack配置文件都是被封装起来的,项目中我们需要使用@src配置根路径,从而方便使用绝对路径的话,就需要去把webpack抽离出来进行修改。
 

  • 执行 npm run eject (此操作是不可逆的!)
  • 执行完成后,项目目录中会多出两个文件夹configscripts
  • config中找到webpack.config.js文件
  • 在alias中添加'@src': path.resolve('src')
alias: {
		// 添加此代码即可
        '@src': path.resolve('src'),
        
        // Support React Native Web
        // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
        'react-native': 'react-native-web',
        // Allows for better profiling with ReactDevTools
        ...(isEnvProductionProfile && {
          'react-dom$': 'react-dom/profiling',
          'scheduler/tracing': 'scheduler/tracing-profiling',
        }),
        ...(modules.webpackAliases || {}),
      },

 
 
 
 

配置好后我们还需要它像相对路径一样有文件别名提示的功能**

一、 首先需要下载插件Path Intellisense

并且需要在插件中打开本地设置并配置
React配置@src根路径_第1张图片

React配置@src根路径_第2张图片

在settings.json中添加

{
    "path-intellisense.mappings": {
        "@src": "${workspaceRoot}/src"
    }
}

 

二、在根目录下创建并配置jsconfig.json文件
{
    "compilerOptions": {
      "target": "ES6",
      "module": "commonjs",
      "allowSyntheticDefaultImports": true,
      "baseUrl": "./",
      "paths": {
        "@src/*": [
          "src/*"
        ]
      }
    },
    "exclude": [
      "node_modules"
    ]
}

你可能感兴趣的:(react,react.js,webpack,javascript)