Hi guys,
I'm trying to find a way to use absolute imports path in my Preact app and I'm having troubles.
Currently my imports look like this
import Loading from '../../../../components/Loading';
and I want to be able to do this
import Loading from 'components/Loading';
To do so, I tried overriding the resolve property in the webpack config
Here is what my preact.config.js look like
import asyncPlugin from "preact-cli-plugin-fast-async";
import path from "path";
export default config => {
asyncPlugin(config);
// tell webpack to watch all of our source
// (by default preact watch only /components)
// this way we can use CSS modules in /containers too
config.module.loaders[4].include = [
path.resolve(__dirname, "src", "containers"),
path.resolve(__dirname, "src", "components")
];
config.module.loaders[5].exclude = [
path.resolve(__dirname, "src", "containers"),
path.resolve(__dirname, "src", "components")
];
config.resolve.alias = {
src: path.resolve(__dirname, "./src/")
};
};
But this give me the following error
Module not found: Error: Can't resolve 'preact-cli-entrypoint'
I suppose that the error is due to the fact that I override all existing aliases, but I can't find a way to make it work. How is this supposed to be done ?
Thanks ! 鉂わ笍
(awesome work with Preact 馃憪 )
Could this https://github.com/developit/preact-cli/issues/491 help you?
You should be able to set your NODE_PATH=src and when you start webpack, those imports should work correctly.
@theochampion Looks like this isn't an issue with the framework/library preact itself, but with the tools that are often used in combination with preact. In this case it looks like you are using preact-cli. That's a separate repository where you'll likely receive more help than here.
Yup - instead of the entire config you posted, just use this:
import path from 'path';
export default config => {
config.resolve.alias.components = path.resolve(__dirname, 'src/components')
}
Thanks @developit
I just rewrote the config file. This will turn all dirs of src to absolute import.
import path from 'path';
import { lstatSync, readdirSync } from 'fs';
const isDirectory = source => lstatSync(source).isDirectory();
const getDirectories = source =>
readdirSync(source).map(name => path.join(source, name)).filter(isDirectory);
export default config => {
getDirectories('src/').map((dir) => {
config.resolve.alias[dir.replace('src/', '')] = path.resolve(__dirname, dir);
});
config.resolve.alias.src = path.resolve(__dirname, 'src');
return config;
};
Most helpful comment
Yup - instead of the entire config you posted, just use this: