У меня не было особого успеха при использовании функции alias
в веб-пакете, она никогда не работала для меня. Вместо этого я использую этот плагин babel: babel-plugin-module-resolver .
Чтобы использовать его, вы создаете пользовательский файл babel.config.js
, например:
module.exports = function(api) {
api.cache(true);
return {
presets: [ "@babel/preset-env", "@babel/preset-react"],
plugins: [
[
"module-resolver",
{
// put your aliases here; I use a tilde (~) to represent
// that the folder is aliased, but you don't have to
alias: {
~actions: "./src/actions",
~components: "./src/components",
~containers: "./src/containers",
~pages: "./src/pages",
~reducers: "./src/reducers",
~root: "./src/root",
~routes: "./src/routes",
~sagas: "./src/sagas",
~styles: "./src/styles",
~types: "./src/types",
~utils: "./src/utils",
},
},
],
"@babel/plugin-transform-runtime",
"@babel/plugin-syntax-dynamic-import",
["@babel/plugin-proposal-class-properties", { loose: true }],
],
};
};
Затем вы можете ссылаться на одну из папок с псевдонимами, например, так: import App from "~components/App"
(при условии, что App
- это папка, содержащая файл index.js
).
Однако, как вы можете видеть, вышеупомянутый подход довольно повторяющийся, когда вам нужно вручную добавлять псевдонимы. Поэтому я создал эту функцию для обхода определенной папки c и создания псевдонимов всех папок верхнего уровня в них:
const { readdirSync, statSync } = require("fs");
const { resolve } = require("path");
// read all directories within the path specified below
// and reduce (loop) through them
const readDirectory = path =>
readdirSync(path).reduce((acc, folder) => {
// combine the path with the current folder name
// for example: "./src/components"
const dirPath = `${path}${folder}`;
// check that the directory (dirPath) exists
if (statSync(resolve(dirPath)).isDirectory()) {
// add the folder as an alias, for example:
// "~components": "./src/components"
// to the accumulator (an object)
acc[`~${folder.replace(/[^\w\s]/gi, "")}`] = dirPath;
}
// return the accumulated object of directories
return acc;
}, {});
// read all top-level directories within "./src/"
const alias = readDirectory("./src/");
module.exports = function(api) {
api.cache(true);
return {
presets: [ "@babel/preset-env", "@babel/preset-react"],
plugins: [
[
"module-resolver",
{ alias } // apply aliased folder to module resolver options object
],
"@babel/plugin-transform-runtime",
"@babel/plugin-syntax-dynamic-import",
["@babel/plugin-proposal-class-properties", { loose: true }],
],
};
};
Что касается примечания, я лично избегаю псевдонимов папок верхнего уровня root ( папки, которые находятся за пределами src
); однако, если вы хотите, то вы можете настроить вышеуказанную функцию, включив в нее список для чтения и игнорирования (потому что вы не хотите использовать псевдонимы node_modules
или .git
папки). Опять же, не рекомендуется и не нужно, если вы просто используете псевдоним в папке src
.