How to add path aliases to next.js? - next.js

Based on docs I know I can use a jsconfig.json file to manage paths.
But I have encountered two problems:
It's a JSON file and not a JS file. This means that I can't code in it. In Vite+React or CRACO we can write Node.js code to create path aliases.
It seems that the paths property does not work for jsconfig.json.
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"#": [
"components"
]
}
}
}
So, my first question is that how can I add path aliases to next.js via code?
And my second question is that why import Button from '#/Button' does not work while I have specified the # to point to compnents directory and the baseUrl to point to the root of the project?
Update
Let's say I have this structure:
- components
- Index
- Exports.js
- Hero.js
- Pricing.js
- Stats.js
- Testimonials.js
- Shared
- Button.js
- Exports.js
- Section.js
- Title.js
- pages
And inside each Exports.js I have exported all sibling modules:
import Hero from './Hero'
import Pricing from './Pricing'
import Stats from './Stats'
import Testimonials from './Testimonials'
export { Hero }
export { Pricing }
export { Stats }
export { Testimonials }
Then why this path alias does not work?
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"Index": [
"components/Index/Exports"
]
}
}
}
And inside index.js:
import { Hero, Pricing, Stats, Testimonials } from 'Index'

Related

How to set path for dynamic import in webpack 4

I have a NET Core application with the following webpack config optimization and output sections located in ClientApp folder which is placed in the root of the project
optimization: {
splitChunks: {
cacheGroups: {
translations: {
test: /[\\/]node_modules[\\/]webapps-translations/,
name(module, chunks, cacheGroupKey) {
const moduleFileName = module.identifier()
.split('\\').pop().toLowerCase().replace('.json', '');
return `${moduleFileName}`;
}
}
}
}
},
output: {
path: path.resolve(path.join('..', 'wwwroot', 'js')),
publicPath: path.join('..', 'js'),
filename: `[name]${jsMin}.js`
}
I have the following dynamic import statement
import(
/* webpackMode: "lazy" */
/* webpackPrefetch: true */
/* webpackPreload: true */
`webapps-translations/assets/${lang}.json`).then(m => {
let translations = m.default;
// TODO: use translations
});
Webpack generates the files in the desire location but the dynamic import request path is wrong. My page URL is http://localhost:5001/api/mypage but the generated import path is http://localhost:5001/api/jsde.js. The generated webpack URL should be http://localhost:5001/js/de.js
How can I configure the right path for dynamic import?

Configure eslint to read common types in src/types/types.d.ts vue3

My eslint .eslintrc.js, now properly in the src folder, is the following:
module.exports = {
env: {
browser: true,
commonjs: true,
es2021: true
},
extends: [
'plugin:vue/vue3-recommended',
'standard',
'prettier'
],
parserOptions: {
ecmaVersion: 2020,
parser: '#typescript-eslint/parser',
'ecmaFeatures': {
'jsx': true
}
},
plugins: [
'vue',
'#typescript-eslint'
],
rules: {
'import/no-unresolved': 'error'
},
settings: {
'import/parsers': {
'#typescript-eslint/parser': ['.ts', '.tsx']
},
'import/resolver': {
'typescript': {
'alwaysTryTypes': true,
}
}
}
}
I'm attempting to use eslint-import-resolver-typescript, but the documentation is a bit opaque.
I currently get errors on lines where a externally defined type is used (StepData in this example):
setup() {
const data = inject("StepData") as StepData;
return {
data,
};
},
The answer was the following. In types.d.ts (or other file if you want to have different collections of your custom types):
export interface MyType {
positioner: DOMRect;
content: DOMRect;
arrow: DOMRect;
window: DOMRect;
}
export interface SomeOtherType {
.. and so on
Then in the .vue files, import the types I need for the component:
import type { MyType, SomeOtherType } from "../types/types";
Before I was not using the export keyword and the types just worked without being imported. They have to be imported like this if you use export. It's kind of amazing how you are just expected to know this, the documentation for Typescript or Vue is sorely lacking in examples.

TypeError: Cannot read property 'forEach' of undefined after upgrade to Nextjs 11

Have upgraded my project to nextjs 11 and unfortunately some of my code is erroring out.
I have equally upgraded React from 16.0.0 version to 17.0.0 so I could then upgrade to next.js.
This is the code snippet that is erroring out and its located in my next.config.js file:
config.module.rules[1].oneOf.forEach((moduleLoader, i) => {
Array.isArray(moduleLoader.use) && moduleLoader.use.forEach((l) => {
if (l.loader.includes("css-loader") && l.options.modules && l.options.modules.exportLocalsConvention) {
l.options = {
...l.options,
modules: {
...l.options.modules,
exportLocalsConvention: "camelCase",
}
}
}
});
});
If I remove the code entirely a different error pops up related to svg config on the same file :
webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
// svg to react component loader
config.module.rules.push({
test: /\.svg$/,
use: [{
loader: '#svgr/webpack',
options: {
"svgoConfig": {
"plugins": [{ "cleanupIDs": false }]
}
}
}],
})
Any ideas on what is happening?
I know they have new related features but not entirely sure how to go about it and ensure my project runs similarly.
Thanks
Next.js 11 now uses webpack 5 under the hood so you need to update your webpack config accordingly.
There is a small migration guide here, but it does not cover all the changes obviously.
I think you can also opt-out of webpack 5 for now, if you want to update Next.js but don't want to mess with webpack config for now:
// add this key in your next.config
module.exports = {
webpack5: false,
}

Qbs custom module not working

I want to make a module to use the QtRO repc compiler to produce .h files from .rep files.
I coded the module but when I try to load it in an application product it does not load and disable the product.
the modules are in C:\Users\User\qt\qbs
Qbs Module replica.qbs:
import qbs
Module {
property bool source: true
FileTagger {
patterns: "*.rep"
fileTags: ["rep"]
}
Rule {
inputs: ["rep"]
Artifact {
fileTags: ["txt_output"]
}
prepare: {
var cmd = new Command();
cmd.program = "repc.exe";
if source {
cmd.arguments = ["-i", "rep", "-o", "source", input.filePath];
} else {
cmd.arguments = ["-i", "rep", "-o", "replica", input.filePath];
}
console.log("repc on : ", input.filePath);
return [cmd];
}
}
}
product.qbs:
import qbs
Application {
name: "ServiceExposer"
Depends { name: "cpp" }
Depends { name: "Qt.core" }
Depends { name: "Qt.remoteobjects" }
Depends { name: "replica" }
files: [
"main.cpp",
"service_exposer.rep"
]
}
project.qbs:
import qbs
Project {
references: ["ServiceExposer/ServiceExposer.qbs"]
qbsSearchPaths: "C:\Users\User\qt\qbs"
}
I don't see where I made the mistake.
Thank you in advance for your help.
If it's a header file, why do you give it the "cpp" tag? Shouldn't it be "hpp"?
What is the reason you are putting the file into the source directory? Do you plan on adding it to your repository? Normally, build artifacts (no matter whether they are binaries or human-readable files) should be located inside the build directory as not to "pollute" the source tree.
You did not mention in what way the module does not work for you now, so it's hard to diagnose the problem. You should mention what you expected to happen and what happened instead (giving the concrete error message, if there is one).
I managed to make it work after digging a little more in the doc and source code, I share with you the working module.
This module when imported if there are any .rep files (QtRO (remote objects)) module remote object definition) in your project, it will invoke the repc compiler and compile them and put the resulting .h file in your source directory.
Still not complete, I didn't find a way to manipulate the files property of the Product Item to add the .h to it automatically.
import qbs
import qbs.FileInfo
Module {
FileTagger {
patterns: ["*.rep"]
fileTags: ["repc-rep"]
}
Rule {
inputs: ["repc-rep"]
Artifact {
filePath: repc_" + FileInfo.baseName(input.fileName) + "_source.h"
fileTags: ["cpp"]
}
prepare: {
var cmd = new Command();
cmd.description = "repc " + input.fileName;
cmd.program = "repc.exe"
cmd.arguments = ["-i", "rep", "-o", "source", input.filePath, output.filePath];
var cmd2 = new JavaScriptCommand();
cmd2.silent = true;
cmd2.sourceCode = function() {
File.copy(output.filePath, FileInfo.path(input.filePath) + "/" + output.fileName);
}
return [cmd, cmd2];
}
}
}
In order to this module to work, the repc.exe must be in your path.
Any suggestion are welcomed.

Brunch not picking up vendor CSS as expected

I'm trying to use Pure.css in my application. I've installed it using npm and have my brunch-config.js configured like so:
stylesheets: {
joinTo: {
'app.css': /^app/,
'vendor.css': /^(?!app)/
}
}
I expect vendor.css to be generated at this point, but it's not. However, if in my JavaScript, I say require('purecss');, then I get vendor.css generated...but I also get the JavaScript error Cannot find module 'purecss' from '<filename>'. I've also tried various permutations of #import 'purecss' in my CSS without success.
How does one consume vendor CSS from npm modules?
You should use npm config section, for example when I wanted to include node_modules/bootstrap/dist/css/bootstrap.css I had to put the following in my brunch-config.js:
npm: {
styles: {
bootstrap: ['dist/css/bootstrap.css']
}
}
That, combined with your section in files makes it write bootstrap's css into vendor.css.
Full brunch-config.js that works for me:
module.exports = {
files: {
javascripts: {
joinTo: {
'app.js': /^app/,
'vendor.js': /^(?!app)/
}
},
stylesheets: {
joinTo: {
'app.css': /^app/,
'vendor.css': /^(?!app)/
}
}
},
plugins: {
babel: { presets: ['es2015'] }
},
npm: {
styles: {
bootstrap: ['dist/css/bootstrap.css']
}
}
};

Resources