How to shorten the absolute path when using webpack v.2? - node.js

I want to use absolute path resolving rules in my project, but when I import a module like this
import Component from "/home/components/Component.js"
it cannot be resolved by webpack, only this works:
import Component from "/users/username/home/components/component.js"
I tried to specify context in my webpack.config, but it made no sense:
context: __dirname
Since I work on windows how do I change my webpack.config to be able to import modules like in the first snippet? In other words how to change my absolute path root for webpack v.2?

You can use resolve.alias to shorten import paths:
webpack.config.js
...
resolve: {
alias: {
home: '/users/username/home/',
},
},
...
Then you will be able to import a module like this:
import Component from "home/components/Component.js"
More information on the official documentation: https://webpack.js.org/configuration/resolve/

Related

Vite: Cannot use import statement outside a module

I know little about bundler and I'm using vite to build project, I got a error when import some package to configure dev server :
SyntaxError: Cannot use import statement outside a module
So here is the thing:
import pinyin from 'pinyin/esm/pinyin-web.js'
export const somePlugin = {
name: 'someplugin',
configureServer(server) {
server.middlewares.use('/somepath', (req, res, next) => {
const foo = pinyin('foo')
next()
})
},
}
I don't use the normal way(import pinyin from 'pinyin') , because that need a package nodejieba which need to install unnecessary node-gyp, so I choose the web version that don't need nodejieba.
I've searched the error, some says add "type": "module" to package.json file. but it already exist in my package.json.
however, I make the change:
// import pinyin from 'pinyin/esm/pinyin-web.js'
import pinyin from 'pinyin/lib/pinyin-web.js'
and problem get solved,I was confused because I thought vite prefer ES module.
So,
1> what cause the problem above?
2> why should I import file with extensions ? eg: import pinyin from 'pinyin/lib/pinyin-web.js'
I have to add extensions .js or it will cause error. while in vite.config.ts I needn't add extensions.
3> I tried to add field optimizeDeps in vite.config.ts like this
export default defineConfig({
plugins: [vue(), somePlugin],
optimizeDeps: {
include: ['pinyin'],
},
})
but it seems to be useless, the offical doc says:
"During development, Vite's dev serves all code as native ESM. Therefore, Vite must convert dependencies that are shipped as CommonJS or UMD into ESM first."
did that work for the frontend part and package "pinyin" is for the dev server so whether add the
field optimizeDeps there is no difference.
codesandbox

Import current module by name in typescript

Is it possible for a module to import "itself" by its own name in typescript?
For instance, lets say there is a module my-module with a bunch of test.
Is there a chance to import it inside the tests using import ... from "my-module" instead of using local path (e.g. import ... from "./my-module")?
As I know it can be done using the require, but it seems that import does not support this.
You can use the TypeScript tsconfig paths option e.g.
{
"paths": {
"module": ["src/path/to/module"]
}
}
More
https://www.typescriptlang.org/docs/handbook/module-resolution.html

What the "#" stands for in paths like "#/assets/xyz"?

Sometimes I see paths written like "#/assets/XXX", and I reckon it refers to the root maybe (in Nodejs)? But i guess it's a syntax that doesn't apply everywhere because when I want to refer to the root folder and try to use it, it sometimes break. I am not sure the implications of it.
The "#" is often used as an alias for a frequently used path (like src/) in webpack environments. You have to define it in your configuration file so the "#" can be resolved in the build-process.
If you work in an ES6 environment and import a component several times, it can be handy to create an alias for the component path.
Example (source: webpack documentation):
resolve.alias
object
Create aliases to import or require certain modules more easily. For example, to alias a bunch of commonly used src/ folders:
webpack.config.js
module.exports = {
//...
resolve: {
alias: {
Utilities: path.resolve(__dirname, 'src/utilities/'),
Templates: path.resolve(__dirname, 'src/templates/')
}
}
};
Now, instead of using relative paths when importing like so:
import Utility from '../../utilities/utility';
you can use the alias:
import Utility from 'Utilities/utility';
You can find a similar answer here: https://stackoverflow.com/a/42753045/10764912

NodeJS How to import JS file into TypeScript

I'm new with TypeScript. I'm currently learning NodeJS Loopback 4 framework which use Typescript language. And my question is how to import some function, class which has been exported in JS file into my TS file. After search several way but it still doesn't work with me.
Here's example:
// /src/index.ts
import {plus} from './lib/test';
console.log(plus(1,2));
// /src/lib/test.js
export function plus(x, y) {
return x + y;
}
I also try using definition typescript like this
// /src/lib/test.d.ts
export declare function plus(x: number, y: number): number;
But still got error when import this function in index.ts file
Error: Cannot find module './lib/test'
at Function.Module._resolveFilename (module.js:543:15)
It looks like the tsconfig.json doesn't have 'allowJs' enabled because it exports declarations.
Is there a reason you are not wanting this to be a typescript file? If you change test.js to test.ts, by making it a .ts should allow it to be recognised in your index file.
UPDATE
Full chat history to get to this point can be found here.
Repository used to test found here
OK so easy solution as #maaz-syed-adeeb mentions will work:
import { path } from './lib/test.js'
The reason the extension is important is because the definition file takes priority over a javascript file in a typescript environment. That is why the module import was blowing up.
To avoid specifying the .js extension you can also setup your directory structure like this:
src
|- index.ts
|- lib
|- test.js
|- test.d.ts
|- index.[js|ts]
in ./lib/index file export all from test:
//./src/lib/index.[js|ts]
export * from './test'
and then import all from lib:
// ./src/index.ts
import { path } from './lib'
// or
import { path } from './lib/test.js'
If you are using a blend of javascript and typescript (say you are moving over to typescript with an existing code base), you will need to update your tsconfig.json to include so you don't get the warnings in your IDE:
{
"compilerOptions": {
"allowJs": true,
"declaration": false
}
}
This is so your javascript files will be transpiled to your destination directory along with the typescript files.

next.js and webpack resolve.modules

I am building a React app using next.js, and I am playing around with the webpack config, in the next.config.js file.
Specifically, I'd like to have nicer imports using webpack's resolve.modules config.
However, when I add the following line in the next.config.js file :
config.resolve.modules
.concat(['styles','static','components','imports'])
and then
import FooBar from 'components/index/FooBar", for example in a pages/index.js file, it still won't work. FooBar is not found.
The component exists, and the import works fine if I use a relative path. However I'd like to have nicer imports, and I know it is possible with webpack (see react-boilerplate for example).
Am I doing something wrong with webpack ? Maybe it's a real bug ?
Check the NextJS example with-absolute-imports
const path = require('path')
module.exports = {
webpack (config, options) {
config.resolve.alias['components'] = path.join(__dirname, 'components')
return config
}
}
Alternatively, should work by adding this to next.config.js file:
config.resolve.modules.push(path.resolve('./'));
(and it doesn't require any babel plugin)
resolve.modules will look into the directories you configured for the modules you import. So when import components/index/FooBar it will look in:
styles/components/index/FooBar
static/components/index/FooBar
components/components/index/FooBar
imports/components/index/FooBar
A relative path looks further, but that's not relevant here and the path remains the same, just climbing up the directory tree (see resolve.modules).
Presumably none of these paths match your component. To get component/index/FooBar you need to import just index/FooBar.
import FooBar from 'index/FooBar';

Resources