subdirectory filename on html-webpack-plugin with dynamic imported chunks - javascript

html-webpack-plugin is capable of handling filename within a sub-directory. However, the default dynamic import seems to be breaking when using it in combination with subdirectory filename. I have tried setting up publicPath and output path, but such settings affect the path of all chunks. I have reproduced the issue with a minimal project below:
webpack.config.js
const HTMLWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/index.js',
plugins: [
new HTMLWebpackPlugin({
filename: 'example/index.html',
})
]
}
src/index.js
console.log('root loaded');
import('./part2.js').then((v) => {
console.log(v);
});
src/part2.js
console.log('part2 loaded');
The above config is correctly creating the html file with relative path main.js. Following is the generated tree structure:
dist
├── 0.js
├── example
│   └── index.html
└── main.js
1 directory, 3 files
But the dynamic chunk is loaded using the following script:
<script charset="utf-8" src="0.js"></script>
which gives an error because it searches for the 0.js as /example/0.js
Failed to load resource: the server responded with a status of 404 (Not Found)
Error: Loading chunk 0 failed.
What should be the correct method to ensure that dynamic imports are correctly loaded?

Related

How to display public images in browser?

I have a following folder structure
.
├── public
├──└──images
├──└── image1.png
├──└── image2.png
├── src
├── vite.config.js
└── [...]
vite.config.js
const path = require('path')
export default {
root: path.resolve(__dirname, 'src'),
server: {
port: 3000,
hot: true
},
publicDir: 'public'
}
How can I access images under public folder ? I tried this from browser
http://127.0.0.1:3000/public/images/image1.png
http://127.0.0.1:3000/images/image1.png
But it gives "Not found"
Can anybody help me ?
According to the docs here
publicDir
Directory to serve as plain static assets. Files in this directory are served at / during dev and copied to the root of outDir during build, and are always served or copied as-is without transform. The value can be either an absolute file system path or a path relative to project root.
So your publicDir must be relative to the root address you set, so you need to either change the root address to the folder above src, or change the publicDir path.

TypeScript: list files in web folder

I have a TypeScript web application with the following folder structure.
- assets
|- a.png
|- b.png
|- c.png
|- d.png
|- ...
- app.ts
In app.ts, how do I programatically list all the files in assets folder?
I tried the below but it didn't work. And I also thought I may be going down the wrong path because fs is used to access the user's file system, which is not my intent.
const fs = require('fs');
const assets_folder = './assets/';
fs.readdirSync(assets_folder).forEach((file) => {
console.log(file);
});
The issue is related to file location because when you use the typescript after compiling., it'll move to dist/build and it'll look in that directory.
Solution: Copy files/directory from src to dist/build programatically, it'll solve your issue.
Project src
src
assets
images
app.ts
After complie
dist
//<Missing assets>
app.js

Is it possible to put test files under pages directory in Next.js?

I'm writing integration tests for the API routes in a Next.js application and I'm wondering if there is any problem with putting the index.test.ts file under the /pages directory. I'd prefer the test to be as close to the file as possible rather than having to map the project structure inside __test__ directory.
./pages/api/path/index.ts
handler.get(async (req: NextApiRequest, res: NextApiResponse) => {
...
});
export default handler;
./pages/api/path/index.test.ts
import { testClient } from "__test__/utils/testClient";
describe("Testing API POST: /api", () => {
test("Should return 401 when not authenticated", async () => {
const request = testClient({ handler });
const res = await request.post("/api/applications");
expect(res.status).toEqual(401);
});
});
TL;DR: While not possible by default, you can co-locate test files inside the pages folder by customising the pageExtensions option in next.config.js.
By default, Next.js will take into account any file ending with tsx, ts, jsx or js under the pages folder for the purpose of building pages/API routes and routing.
From the Custom Page Extensions documentation:
Next.js assumes every tsx/ts/jsx/js file in the pages directory is a
page or API route, and may expose unintended routes vulnerable to
denial of service attacks, or throw an error like the following when
building the production bundle
Adding a file named index.test.ts in the pages folder (or any subfolder) will include that file as an actual page, and potentially throw errors during build time.
You can circumvent this by modifying the extensions Next.js expects using the pageExtensions property in next.config.js.
module.exports = {
// Default value is ['tsx', 'ts', 'jsx', 'js']
pageExtensions: ['page.tsx', 'page.ts', 'page.jsx', 'page.js']
}
With this configuration, only pages with the above extensions will be taken into account. So you could have the following pages folder structure, with co-located test files.
pages/
├─ api/
│ ├─ path.page.ts
│ └─ path.test.ts
├─ _app.page.ts
├─ _document.page.ts
├─ index.page.ts
└─ index.test.ts
Both path.test.ts and index.test.ts would be ignored.

Vue CLI 3 SPA in Subfolder, Static HTML Pages in Root

Using Vue CLI 3 how can I create a project that contains some static html files at the root of the public directory and an SPA inside of an app folder?
I'd like several static html files including an index.html at the root of the project. I want these static HTML files served outside of the SPA for SEO purposes.
Right now, my project structure looks like this:
.
├── README.md
├── babel.config.js
├── package.json
├── public
│   ├── app
│   │   └── index.html
│   ├── favicon.ico
│   └── index.html
├── src
│   ├── App.vue
│   ├── assets
│   │   └── logo.png
│   ├── components
│   │   └── HelloWorld.vue
│   └── main.js
├── vue.config.js
└── yarn.lock
I've tried many different combinations of publicPath and indexPath values in my vue.config.js file. None have achieved what I'm hoping for. I'd like yarn serve to serve both the static HTML files and SPA locally for development. More importantly, I'd like the static HTML files and the SPA properly bundled into the dist folder when I run yarn build. I haven't been able to achieve either goal.
With the configuration below, the public/index.html file that's meant to be static and only displaying at / is being served at both http://localhost:8080/ and http://localhost:8080/app/. Interestingly, at http://localhost:8080/app/ the js resources are being injected into the response along with what's meant to be static HTML.
After running yarn build with the config below I'm left with a /dist/app/index.html file that has the static index.html file code with no javascript injected instead of the SPA code with javascript injected. The /dist/index.html file has the static HTML I expect but all the javascript that's meant for the SPA is injected.
// vue.config.js
module.exports = {
publicPath: '/app/',
indexPath: 'index.html'
}
How can I configure this project to support static html files at the project root and an SPA in the app folder?
You can leverage the feature of Vue CLI to build multipage apps and actually have only one page...
// vue.config.js
module.exports = {
pages: {
index: {
// entry for the page
entry: "src/main.js",
// the source template
template: "public/app/index.html",
// output as dist/app/index.html
filename: "app/index.html",
// when using title option,
// template title tag needs to be <title><%= htmlWebpackPlugin.options.title %></title>
title: "App Index Page",
// chunks to include on this page, by default includes
// extracted common chunks and vendor chunks.
chunks: ["chunk-vendors", "chunk-common", "index"]
}
}
};

OpenShift unable to find css and js files

When running my openshift app none of the CSS or javescript files are loading.
I have specified the directory in the server.js:
app.use(express.static(__dirname));
In the index.html I have specified the location of the folders:
<link rel="stylesheet" href="style.css" type="text/css" media="screen">
<script src = "controllers/controller.js"></script>
The structure of the folder looks like:
mytest
├── README.md
├── controllers
│   └── controller.js
├── deplist.txt
├── index.html
├── node_modules
├── package.json
├── server.js
└── style.css
When I open the website and open the developer console in chrome I get the following errors:
http://mytest-jamestreasure.rhcloud.com/controller.js 404 Not Found
http://mytest-jamestreasure.rhcloud.com/controllers/controller.js 404 Not Found
I'm not aware of anything else that needs to be added.
Link to the my openshift: http://mytest-jamestreasure.rhcloud.com/
Your construct for defining static content access seems to be correct. Make sure that you are using it with your app context though, e.g.:
myApp.app.use(express.static(__dirname));
Such a problem could be revealed either locally when trying to run the server.js or using rhc tail mytest to check the OpenShift remote logs.
I would also recommend using a dedicated directory for static content that is meant to be used publicly, rather than exposing everything:
app.use(express.static(__dirname + '/public'));
The issue was because of the following warning, which I was ignoring:
Warning: express.createServer() is deprecated, express
applications no longer inherit from http.Server,
please use:
var express = require("express");
var app = express();
It meant I had to change:
self.app = express.createServer();
to:
self.app = app;
This was in the self.initialise = function()

Categories

Resources