Vite resolve static asset path - javascript

In vite.config.js i have set up:
resolve: {
alias: [
{ find: '~ext', replacement: path.resolve(__dirname, './src/assets/ext') },
Now I try to resolve a path (not a file!) in main.js:
import myDir from '~ext/SomeDir/'
console.log(myDir);
Could not load C:\prj\MyProject\src\assets\ext/SomeDir(imported by src/assets/js/main.js):
EISDIR: illegal operation on a directory, read
Resolving a file ~ext_/SomeDir/somefile.txt_ works fine.
Is there a way to get the path resolved in Vite?
(without having a dummy file and stripping the filename)?
import myDir from '~ext/SomeDir/?url' gives me /#fs/assets/ext/SomeDir/, so I have to remove the #fs there too I guess

Related

How can I use absolute imports with storybook and Next.js?

In my .storybook/main.js file, I have:
webpackFinal: async (config) => {
config.resolve.modules = [
...(config.resolve.modules || []),
path.resolve(__dirname),
];
return config;
},
But when I run my storybook, I get an error:
resolve 'components/Common/Button' in '/myprojectpath/pages'
Parsed request is a module
using description file: /myprojectpath/package.json (relative path: ./pages)
Field 'browser' doesn't contain a valid alias configuration
resolve as module
/myprojectpath/pages/node_modules doesn't exist or is not a directory
looking for modules in /myprojectpath/node_modules
Not sure what's happening. When I run the Next.js project, it loads fine.
Thanks in advance!
It looks like the setting absolute path issue: github issue
Most likely, will be solved with
path.resolve(__dirname, ".."), "node_modules"]
or
path.resolve(__dirname, "../src"), "node_modules"]

webpack and importing js files to scripts and bundling up

I'm pretty inexperienced with webpack. I'm actually using Cloudflare Wrangler, which I believe uses Webpack 4 under the hood. In any case I have an src/index.js file and a helpers/script.js file.
my index.js file works fine, builds and compiles etc etc.
When I copy the content of helpers/script.js into the top of the index.js file, again all is good and works.
When I import script.js with either of
import human from "../helpers/script"
const human = require("../helpers/script")
then I use a webpack.config.js file that looks like
module.exports = {
target: 'webworker',
context: __dirname,
entry: './src/index.js',
mode: 'production',
module: {
rules: [
{
test: /\.index\.js$/,
use: { loader: 'worker-loader' }
}
],
},
resolve: {
extensions: ['.js'],
},
};
I can't seem, no matter what I do to get it to 'like' the imported script file.
I continually get:
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
...
Error: webpack returned an error. Try configuring `entry` in your webpack config relative to the current working directory, or setting `context = __dirname` in your webpack config.
Can anyone help me understand the requirements for being able to import a file to another js. Its amazing how hard this is to do :joy:

How to change the entry point to something other than the default 'src/main.js' using Vite?

I want to point to a different location and file name and deviate from the Vite standard.
Let's say my js file is in out/frontend/../../out.js. I got it working when I rename it to main.js and copy it in the root of my project where index.html and vite.config.js live. But I would prefer to change the entry point somehow...
I tried this:
rollupInputOptions: {
// or whatever your entry file is
input: resolve(__dirname, 'out/frontend/my/path/out.js')
}
Did not work. Any suggestions?
As of Vite 2, the entry file is specified in a <script> tag in index.html:
<script type="module" src="/src/main.js"></script>
You can change that file to the one you want:
<script type="module" src="/out/frontend/my/path/out.js"></script>
demo
Use resolve from path module and add an alias in vite.config.js config to resolve paths, check.
import { resolve } from 'path'
module.exports = {
...
resolve: {
alias: {
'#': resolve(__dirname, '../out/'), // resolve path
},
},
rollupInputOptions: {
input: resolve(__dirname, '../out/entrypoint.js') // custom main
}
}
to import a module from resolved path use '#', eg: import { myModule } from '#/mymodule'
You will have to adjust the path of the new entrypoint in the index.html file.

webpack5 output.library can't import

problem
I use <script> to import index.bundle.js which bundled by webpack5 in a HTML.But I failed.
option file
//webpack.config.js
const path = require('path');
module.exports = {
entry: {
index: '/src/index.ts'
},
output: {
path: path.join(__dirname, 'dist'),
library: 'test',
libraryTarget: 'umd',
}
}
//index.ts
export function mount() {
console.log("mount")
}
//html
<script src="dist/index.js"></script>
<script>
console.log(window.mount());
</script>
error
Uncaught TypeError: window.mount is not a function
code
I have checked the official documentation.But I can't find answer.
my code is here
use
yarn
npm run build
then open the index.html,you can find the error.
Using the config you currently have (which is not putting them on the root window object), you can access your functions with window.test.mount(), because that's what you have in library in the webpack config.
If you want to put these functions on the root window object, you'd need to do that in your code:
export function mount() {
console.log("mount")
}
window.mount = mount
// etc.
You can see this by checking out dist/index.js (dropping it in the Prettier tool online can clean it up enough to be readable).

How to separate source file from all vendors in webpack?

I want to have two files app.bundle.js and vendors.js where app.bundle.js contains only the code I wrote. Is it possible?
Here is my webpack.config.js file now
const dependencies = _.keys(packageConfig["dependencies"])
export default {
entry: {
vendors: dependencies,
app: [
'webpack-hot-middleware/client',
'./src/js/entry.js'
]
},
output: {
path: path.join(__dirname, 'dist'),
filename: '[name].bundle.js',
publicPath: '/'
},
...
plugins: [
new webpack.optimize.CommonsChunkPlugin('vendors', 'vendors.js'),
...
But it does not work. I always had an error when compiling because some modules are not found. I've tried to list all dependencies manually, but in such case I have third party code in my app.bundle.js. So is it even possible?
UPDATE
I've take a look into the compiled app.bundle.js and saw code from hot replacement module and webpack itself. So the real question is - is this a default code that have to be placed inside each webpack module?
UPDATE
My first line in the entry file is import 'babel-core/polyfill' so I want module babel-core to be in vendors.js. And have this error
ERROR in ./~/babel-core/~/regenerator/lib/visit.js
Module not found: Error: Cannot resolve module 'fs' in /Users/vitalii/Documents/coding/timerrrs/node_modules/babel-core/node_modules/regenerator/lib
# ./~/babel-core/~/regenerator/lib/visit.js 12:9-22
ERROR in ./~/babel-core/~/regexpu/data/iu-mappings.json
Module parse failed: /Users/vitalii/Documents/coding/timerrrs/node_modules/babel-core/node_modules/regexpu/data/iu-mappings.json Line 2: Unexpected token :
You may need an appropriate loader to handle this file type.
| {
| "75": 8490,
| "83": 383,
| "107": 8490,
# ./~/babel-core/~/regexpu/rewrite-pattern.js 4:17-51
ERROR in ./~/babel-core/~/globals/globals.json
Module parse failed: /Users/vitalii/Documents/coding/timerrrs/node_modules/babel-core/node_modules/globals/globals.json Line 2: Unexpected token :
You may need an appropriate loader to handle this file type.
| {
| "builtin": {
| "Array": false,
| "ArrayBuffer": false,
# ./~/babel-core/~/globals/index.js 1:17-42
ERROR in ./~/babel-core/~/regenerator/~/recast/main.js
Module not found: Error: Cannot resolve module 'fs' in /Users/vitalii/Documents/coding/timerrrs/node_modules/babel-core/node_modules/regenerator/node_modules/recast
# ./~/babel-core/~/regenerator/~/recast/main.js 18:4-17

Categories