customize-cra icon indicating copy to clipboard operation
customize-cra copied to clipboard

addWebpackAlias doesn't work

Open haoyinag opened this issue 5 years ago • 19 comments

my code's here ...

const { override, fixBabelImports, addWebpackExternals, addWebpackAlias, addLessLoader } = require('customize-cra'); const path = require('path'); const UglifyJsPlugin = require('uglifyjs-webpack-plugin'); const { paths } = require('react-app-rewired'); console.log(paths.appSrc);

const myPlugin = [ new UglifyJsPlugin({ uglifyOptions: { warnings: false, compress: { drop_debugger: true, drop_console: true } } }) ];

module.exports = override( fixBabelImports('import', { libraryName: 'antd', libraryDirectory: 'es', style: true }), addWebpackExternals({ echarts: 'window.echarts' // highcharts:"window.highcharts" }), addWebpackAlias({ '@': ${paths.appSrc} // doesn't work }), addLessLoader({ javascriptEnabled: true, modifyVars: { '@primary-color': '#1DA57A' } }), config => { // config.devtool = config.mode === 'development' ? 'cheap-module-source-map' : false; if (process.env.NODE_ENV === 'production') config.devtool = false; if (process.env.NODE_ENV !== 'development') config.plugins = [...config.plugins, ...myPlugin]; const loaders = config.module.rules.find(rule => Array.isArray(rule.oneOf)) .oneOf; loaders[5].use.push({ loader: 'sass-resources-loader', options: { resources: path.resolve(__dirname, 'src/asset/base.scss') } });

return config;

} );

use alias import { router } from '@/maps'; the wrong msg: Cannot find module '@/maps'

haoyinag avatar Jan 09 '20 10:01 haoyinag

my code works correctly

// config-overrides.js
const {
  override,
  fixBabelImports,
  addLessLoader,
  addWebpackModuleRule,
  addWebpackAlias,
  addWebpackPlugin,
  // eslint-disable-next-line import/no-extraneous-dependencies
} = require('customize-cra');
const path = require('path');
const AntdDayjsJalaliWebpackPlugin = require('antd-dayjs-webpack-plugin');

module.exports = override(
  config => ({
    ...config,
    output: {
      ...config.output,
      globalObject: 'this',
    },
  }),
  // addWebpackModuleRule({
  //   test: /\.worker\.js$/,
  //   use: { loader: 'worker-loader' },
  // }),
  fixBabelImports('import', {
    libraryName: 'antd',

    libraryDirectory: 'es',
    style: true,
  }),
  addLessLoader({
    javascriptEnabled: true,
    modifyVars: {
      'primary-color': '#09b39d',
    },
  }),
  addWebpackPlugin(new AntdDayjsWebpackPlugin()),
  addWebpackAlias({
       '@': path.resolve(__dirname, './src/'),
       '@components': path.resolve(__dirname, './src/components/index/public'),
  }),
);

Yumcoder-dev avatar Jan 09 '20 12:01 Yumcoder-dev

@YumcoderCom i don't know what is problem , image

even i used your code , still can not work

haoyinag avatar Jan 10 '20 02:01 haoyinag

Have you found a solution,I have the same problem。

smallmonsters avatar Feb 14 '20 09:02 smallmonsters

@haoyinag this actually worked??

fixBabelImports('import', {
libraryName: 'antd',
libraryDirectory: 'es',
style: true
}),

I can't even get just that to work

FlyingUnicornSF avatar Mar 28 '20 01:03 FlyingUnicornSF

@FlyingUnicornSF it worked

haoyinag avatar Apr 01 '20 02:04 haoyinag

We need 2 steps to add aliases

  1. tell to IDE about aliases in tsconfig.json
  2. tell to webpack about aliases

First:

create separate file tsconfig.path.json and add aliases:

{
   "compilerOptions": {
      "baseUrl": "./src",
      "paths": {
         "@utils/*": ["utils/*"]
      }
   }
}

Add created tsconfig.path.json to main tsconfig.json

{
   "extends": "./tsconfig.paths.json",
   ... other staff ...
}

Second:

Add aliases to config-overrides.js

const {
   override,
   addWebpackAlias
} = require('customize-cra');

const path = require("path");

module.exports = override(
   addWebpackAlias({
      "@utils": path.resolve(__dirname, "./src/utils"),
   }),
);

It works for me, happy coding ;)

gyerts avatar May 13 '20 09:05 gyerts

@gyerts I can't use it,here is my codes

config-overrides.js

const {
	override,
	addWebpackAlias,
	addLessLoader
} = require('customize-cra');
const path = require("path");

module.exports = override()(
	addLessLoader(),
	addWebpackAlias({
		"@pages": path.resolve(__dirname, "./src/pages"),
	}),
);

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react"
  },
  "include": [
    "src"
  ],
  "extends": "./tsconfig.path.json"
}

tsconfig.path.json

{
  "compilerOptions": {
    "baseUrl": "./src",
    "paths": {
      "@pages/*": ["pages/*"]
    }
  }
}
import blogDetail from '@pages/blogDetail'

./src/containers/layout.tsx wrong msg: Module not found: Can't resolve '@pages/blogDetail'

kechen123 avatar May 14 '20 02:05 kechen123

@kechen123 First i see: You use module.exports = override()() I use module.exports = override() Second, my tsconfig.json

{
  "extends": "./tsconfig.paths.json",
  "compilerOptions": {
    "sourceMap": true,
    "outDir": "./build/",
    "target": "es5",
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "experimentalDecorators": true,
    "jsx": "preserve",
    "lib": [
      "es5",
      "es6",
      "dom",
      "es2015"
    ],
    "noImplicitAny": false,
    "isolatedModules": true,
    "noEmit": true
  },
  "include": [
    "./src/**/*"
  ],
  "exclude": [
    "./src/resources/**/*"
  ],
  "awesomeTypescriptLoaderOptions": {
    "reportFiles": [
      "./src/**/*"
    ]
  }
}

Could you try my way, and than will see next steps

gyerts avatar May 14 '20 07:05 gyerts

@gyerts wow . I didn't notice it ,it work

kechen123 avatar May 15 '20 01:05 kechen123

We need 2 steps to add aliases

  1. tell to IDE about aliases in tsconfig.json
  2. tell to webpack about aliases

First:

create separate file tsconfig.path.json and add aliases:

{
   "compilerOptions": {
      "baseUrl": "./src",
      "paths": {
         "@utils/*": ["utils/*"]
      }
   }
}

Add created tsconfig.path.json to main tsconfig.json

{
   "extends": "./tsconfig.paths.json",
   ... other staff ...
}

Second:

Add aliases to config-overrides.js

const {
   override,
   addWebpackAlias
} = require('customize-cra');

const path = require("path");

module.exports = override(
   addWebpackAlias({
      "@utils": path.resolve(__dirname, "./src/utils"),
   }),
);

It works for me, happy coding ;)

that work for me, Thanks : )

jenwit07 avatar Aug 10 '20 10:08 jenwit07

We need 2 steps to add aliases

  1. tell to IDE about aliases in tsconfig.json
  2. tell to webpack about aliases

First:

create separate file tsconfig.path.json and add aliases:

{
   "compilerOptions": {
      "baseUrl": "./src",
      "paths": {
         "@utils/*": ["utils/*"]
      }
   }
}

Add created tsconfig.path.json to main tsconfig.json

{
   "extends": "./tsconfig.paths.json",
   ... other staff ...
}

Second:

Add aliases to config-overrides.js

const {
   override,
   addWebpackAlias
} = require('customize-cra');

const path = require("path");

module.exports = override(
   addWebpackAlias({
      "@utils": path.resolve(__dirname, "./src/utils"),
   }),
);

It works for me, happy coding ;)

that work for me, Thanks : )

pingan8787 avatar Sep 10 '20 06:09 pingan8787

Anyone is reading this and is wondering.. why use the seperate file? why not just put it in the tsconfig.json? Because that file gets mostly rewritten each run, and it will delete the paths you add. You gotta keep it in an external file, unfortunately.

the-simian avatar Sep 11 '20 02:09 the-simian

We need 2 steps to add aliases

  1. tell to IDE about aliases in tsconfig.json
  2. tell to webpack about aliases

First:

create separate file tsconfig.path.json and add aliases:

{
   "compilerOptions": {
      "baseUrl": "./src",
      "paths": {
         "@utils/*": ["utils/*"]
      }
   }
}

Add created tsconfig.path.json to main tsconfig.json

{
   "extends": "./tsconfig.paths.json",
   ... other staff ...
}

Second:

Add aliases to config-overrides.js

const {
   override,
   addWebpackAlias
} = require('customize-cra');

const path = require("path");

module.exports = override(
   addWebpackAlias({
      "@utils": path.resolve(__dirname, "./src/utils"),
   }),
);

It works for me, happy coding ;)

that work for me, Thanks : )

FE92star avatar Dec 08 '20 13:12 FE92star

thank you @FE92star for the details and guidance for all, if anyone else using vs code and still having issues after this; restart vs code and autocomplete should work also.

ghost avatar Dec 29 '20 19:12 ghost

hello, pic2 is ok, but in pic1 , the * in the middle of path(./../../../packages/*/src) cannot resolve , can I use another way to solve it? @FE92star @gyerts thank you very much!

   addWebpackAlias({
      "@": path.resolve(__dirname, "./src"),
      "@zeus/*": path.resolve(__dirname, "../../../../packages/*/src"),
      "@zeus/components/*": path.resolve(
        __dirname,
        "../../../../packages/components/src/*"
      ),
    }),
{
  "compilerOptions": {
    "baseUrl": "./",
    "paths": {
      "@/*": ["./src/*"],
      "@zeus/*": ["../../../../packages/*/src"],
      "@zeus/components/*": ["../../../../packages/components/src/*"]
    }
  }
}

lonelygoogle avatar Feb 22 '22 11:02 lonelygoogle

@gyerts excuse me, can you help me?

config-overrides.js

/* eslint-disable @typescript-eslint/no-var-requires */
const { addWebpackAlias, override } = require("customize-cra");
const path = require("path");

const resolve = (src) => path.resolve(__dirname, src);

module.exports = override(
  addWebpackAlias({
    "@Atoms": resolve("./src/Components/Atoms"),
    "@Molecules": resolve("./src/Components/Molecules"),
    "@Organisms": resolve("./src/Components/Organisms"),
    "@Templates": resolve("./src/Components/Templates"),
    "@Pages": resolve("./src/Components/Pages"),
    "@Constant": resolve("./src/Common/Constant"),
    "@Style": resolve("./src/Common/Style"),
    "@Util": resolve("./src/Common/Util"),
    "@Type": resolve("./src/Common/Type"),
    "@API": resolve("./src/API"),
    "@Route": resolve("./src/Routes"),
    "@Recoil": resolve("./src/Recoil"),
    "@src": resolve("./src"),
  })

// tsconfig.path.json

{
  "compilerOptions": {
    "baseUrl": "./src",
    "paths": {
      "@Atoms/*": ["Components/Atoms/*"],
      "@Molecules/*": ["Components/Molecules/*"],
      "@Organisms/*": ["Components/Organisms/*"],
      "@Templates/*": ["Components/Templates/*"],
      "@Pages/*": ["Components/Pages/*"],
      "@Constant/*": ["Common/Constant/*"],
      "@Style/*": ["Common/Style/*"],
      "@Util/*": ["Common/Util/*"],
      "@Type/*": ["Common/Type/*"],
      "@API/*": ["API/*"],
      "@Route/*": ["Routes/*"],
      "@Recoil/*": ["Recoil/*"],
      "@src/*": ["*"]
    }
  }
}

// tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
  },
  "extends": "./tsconfig.paths.json",
  "include": ["src"]
}

I want to work... plz

jin-Pro avatar Mar 04 '22 18:03 jin-Pro

OMG

image

jin-Pro avatar Mar 05 '22 06:03 jin-Pro

We need 2 steps to add aliases

  1. tell to IDE about aliases in tsconfig.json
  2. tell to webpack about aliases

First:

create separate file tsconfig.path.json and add aliases:

{
   "compilerOptions": {
      "baseUrl": "./src",
      "paths": {
         "@utils/*": ["utils/*"]
      }
   }
}

Add created tsconfig.path.json to main tsconfig.json

{
   "extends": "./tsconfig.paths.json",
   ... other staff ...
}

Second:

Add aliases to config-overrides.js

const {
   override,
   addWebpackAlias
} = require('customize-cra');

const path = require("path");

module.exports = override(
   addWebpackAlias({
      "@utils": path.resolve(__dirname, "./src/utils"),
   }),
);

It works for me, happy coding ;)

Hi. Is there any way to manage it in one file?

yuda1124 avatar Aug 14 '22 14:08 yuda1124

We need 2 steps to add aliases

  1. tell to IDE about aliases in tsconfig.json
  2. tell to webpack about aliases

First:

create separate file tsconfig.path.json and add aliases:

{
   "compilerOptions": {
      "baseUrl": "./src",
      "paths": {
         "@utils/*": ["utils/*"]
      }
   }
}

Add created tsconfig.path.json to main tsconfig.json

{
   "extends": "./tsconfig.paths.json",
   ... other staff ...
}

Second:

Add aliases to config-overrides.js

const {
   override,
   addWebpackAlias
} = require('customize-cra');

const path = require("path");

module.exports = override(
   addWebpackAlias({
      "@utils": path.resolve(__dirname, "./src/utils"),
   }),
);

It works for me, happy coding ;)

First, here is a typo.

image

Second, I think the file tsconfig.paths.json is unnecessary if you don't have too many paths to config.

you can just config the two file tsconfig.json and config-overrides.js, as I did:

  • tsconfig.json
{
  "compilerOptions": {
    ...otherConfigs
    "baseUrl": "./src",
     "paths": {
        "@pages/*": ["pages/*"]
     }
  }
}
  • config-overrides.js
const path = require("path");
/* global require, module, __dirname */
const {
  override,
  addWebpackAlias,
} = require("customize-cra");

module.exports = override(
  addWebpackAlias({
    ["@pages"]: path.resolve(__dirname, "./src/pages"),
  })
);

it also works for me.

bingDBdu avatar Jan 17 '24 03:01 bingDBdu