频道
bg

Root Import

coding一月 30, 20211mins
Frontend

Root ImportH1

Created: January 30, 2021 4:20 PM Category: 前端

如果要设置从根目录开始的路径(而不是相对路径)导入模块,需要配置

  • tsconfig.json/jsconfig.json IDE/tsserver需要
  • tsconfig.json tsload需要
  • webpack alias 模块加载需要

GatsbyH2

Webpack v4 drops resolve.root in favor of resolve.alias found here.

If no options are specified, the plugin creates a default alias of src to your project src folder.

因此gatsby-plugin-root-import 在Gatsby V2中使用的时候只是恰好默认映射了src而不是映射的根目录

TypescriptH2

This is already supported using paths mapping. in your tsconfig.json/jsonfig.json add an entry to your path mapping rules to match the ~ to whatever root you need. e.g.:

jsx

{
"compilerOptions": {
"baseUrl": "./", // all paths are relative to the baseUrl
"paths": {
"~/*" : ["*"] // resolve any `~/foo/bar` to `<baseUrl>/foo/bar`
}
}
}

Support custom root directory alias for imports · Issue #14907 · microsoft/vscode

模块解析

补充H2

使用jsconfig.json或者tsconfig.json 后,设置webpack自动根据compilerOptions#baseurl 设置alias

java

// https://gist.github.com/nerdyman/2f97b24ab826623bff9202750013f99e
const { resolve } = require('path');
/**
* Resolve tsconfig.json paths to Webpack aliases
* @param {string} tsconfigPath - Path to tsconfig
* @param {string} webpackConfigBasePath - Path from tsconfig to Webpack config to create absolute aliases
* @return {object} - Webpack alias config
*/
function resolveTsconfigPathsToAlias({
tsconfigPath = './tsconfig.json',
webpackConfigBasePath = __dirname,
} = {}) {
const { paths } = require(tsconfigPath).compilerOptions;
const aliases = {};
Object.keys(paths).forEach((item) => {
const key = item.replace('/*', '');
const value = resolve(webpackConfigBasePath, paths[item][0].replace('/*', '').replace('*', ''));
aliases[key] = value;
});
return aliases;
}
module.exports = resolveTsconfigPathsToAlias;

或者使用awesome-typescript-loader代替ts-loader, 因为awesome-typescript-loader中提供TsConfigPathsPlugin插件,该插件可以将tsconfig.json中的路径映射copy到webpack.resolve.alias

或者也可以设置NODE_PATHhttps://github.com/facebook/create-react-app/issues/2188

评论


新的评论

匹配您的Gravatar头像

Joen Yu

@2022 JoenYu, all rights reserved. Made with love.