timbai
timbai

react + typescript + webpack 如何設定 webpack alias

前言

create react app 是一個可以快速設定 react 專案的一個工具,在建立專案時已經把 babel,webpack 都已經預先封裝設置好,如果我們要修改 webpack alias 設定該如何設定呢

什麼是 alias

alias 在 webpack 設定意義叫做,檔案路徑別名系統,意思就是可以使用一種別稱,讓 webpack 抓取這個別稱找到這個檔案路徑,這篇章節教大家如何設定 webpack alias 可以不需要那麼辛苦的一直點點斜

例子

// 平常引入檔案方式
import Menu from '../../components/Menu.jsx'
// 使用 alias 之後
import Menu from '@/components/Menu.jsx'

建置步驟

建置步驟有四部,我會一步一步教大家

建立 react 專案

建立新的 react 專案並開啟專案,crate-react-app 為建立專案工具,react-demo 專案名稱,建立好之後將專案打開

create-react-app react-demo

執行 npm run eject 指令

在此專案可打開 package.json 裡面有個 scripts 部分,裡面提供了一些指令

"scripts": {
 "start": "react-scripts start",
 "build": "react-scripts build",
 "test": "react-scripts test",
 "eject": "react-scripts eject"
}

在這裡面可以看到 eject 這個 script,使用 npm 執行以下使令,會將 webpack 設定建置好

npm run eject

安裝 tsconfig-paths-webpack-plugin 套件

使用 npm 安裝 tsconfig-paths-webpack-plugin 套件,這個套件可以設置那些副檔可以執行 alias

npm install tsconfig-paths-webpack-plugin

接著打開 config/webpack.config.js 檔案,先將 tsconfig-paths-webpack-plugin 套件引入

const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');

再往下滑到 alias 物件設定自定義檔案別名

alias: {

        // 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 || {}),

          // 自定義絕對路徑

        '@': paths.appSrc

}

在滑到 plugins 設定 tsconfig-paths-webpack-plugin 套件,設定可支援 alias 之副檔

plugins: [

    // Prevents users from importing files from outside of src/ (or node_modules/).

    // This often causes confusion because we only process files within src/ with babel.

    // To fix this, we prevent you from importing files out of src/ -- if you'd like to,

    // please link the files into your node_modules/ and let module-resolution kick in.

    // Make sure your source files are compiled, as they will not be processed in any way.

    new ModuleScopePlugin(paths.appSrc, [

        paths.appPackageJson,

        reactRefreshRuntimeEntry,

        reactRefreshWebpackPluginRuntimeEntry,

        babelRuntimeEntry,

        babelRuntimeEntryHelpers,

        babelRuntimeRegenerator,

    ]),


    // 自定義副檔存取快取路徑

    new TsconfigPathsPlugin({

        extensions: ['.js', '.jsx', '.json', '.ts', '.tsx', '.sass', '.scss', '.css']

    })

]

最後設定 tsconfig.json 檔案

我們須加上 baseUrl 和 paths 這兩個物件,baseUrl 為這個專案初始路徑,paths 則是設定檔案路近別名,設定好以下就可以使用啦

"baseUrl": ".",
"paths": {
    "@/*": ["src/*"]
}
CC BY-NC-ND 4.0 版权声明

感謝大家的支持,我會為大家寫有幫助的文章,你(妳)們的支持是我寫作的動力

加载中…

发布评论