Using Vite.js HMR with SCSS in a WordPress theme - wordpress

I'm trying to use Vite.js in a WordPress theme to process my asset files.
I've created a vite.config.js file:
import { defineConfig } from 'vite';
export default defineConfig({
root: './resources',
build: {
rollupOptions: {
input: ['./resources/test.scss'],
},
},
server: {
port: 1337,
},
});
And I'm loading the Vite.js client plus the asset from the server:
<script type="module" src="http://127.0.0.1:1337/#vite/client"></script>
<link rel="stylesheet" href="http://127.0.0.1:1337/test.css?ver=6.0.1">
But this results in a 404 error for the test.css file. When using a css/js file instead of scss, everything including HMR works fine. I'm also not getting any warning about sass needing to be installed, so I assume Vite.js skips the scss file completely for some reason.
Is it a good idea to use the rollupOptions.input option for just listing resources in the first place or is there a better way? As I'm not building a JS application, there's no entry point such as an index.html, just some js/scss files I want to process.

You need to install SASS npm add -D sass https://vitejs.dev/guide/features.html#css-pre-processors.
The input file is a JavaScript file input: 'main.js', that itself imports the SCSS files import './resources/test.scss';.
Generally, the backend integration guide would help you with the setup for a multipage app like WordPress https://vitejs.dev/guide/backend-integration.html.

Related

Custom font not working on live version of Laravel 9 Website

Problem
So i've got a custom-font.ttf in my public/fonts directory The font loads and works fine on local host.
When deployed to heroku it's throwing a 404 error in console, and i noticed it's trying to access custom-font.ttf in build/assets/fonts/..
relevant part of app.css :
#font-face {
src: url(/fonts/Satoshi-Variable.ttf);
font-family: satoshi;
}
vite.config.js
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
export default defineConfig({
plugins: [
laravel({
input: ['resources/js/app.js'],
refresh: true,
}),
],
});
app.js
import './bootstrap';
import '../css/app.css';
Question
How do I make the live site use the font from public/fonts?
Or how do i add the font to vite properly so it includes it in the build folder?
Rather than force the app to look in a different folder, why not put it under your root src directory in a folder called assets? It should pick it up automatically then and put it where it belongs.

Link css stylesheet with express.static problem

I'm just learning, so need some help with something.
When I try to load my html file on my local server it doesn't load my styles.css file.
I used the express.static on my "public" folder and modified the path of the styles.css in the html file. Some help would be great . Thanks.
The folder paths: css
C:\Newsletter-Signup\public\css\styles.css
html file that i tryed to load with applied .css on it:
C:\Newsletter-Signup\public\signup.html
!(https://imgur.com/PJO7J4H)
this is my app.js file:
const app = express();
app.use(express.static("public"));
app.get("/", function(req, res){
res.sendFile(__dirname + "/signup.html" );
});
app.listen("3000", function(){
console.log("server started on port 3000");
});
and this is my link to styles.css that doesnt load:
< link href="css/styles.css" rel="stylesheet" >
Here I am trying to present you a generic solution.So this may be helpful to fix the issue, which occurs during your code attempt.
When generating the express app project, I used the command npm install -g express-generator which recommended in Express Js official site. From that, I could easily create the folder structure for the express app.
.pug file format
By default the generated express app only allows you to render .pug file format instead of .html file. Express-generator installs pug node module via npm install pug -- save while installs other required dependencies. After installs pug dependency you are allowed render .pug files locate in the root using localhost URL.
app.js
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res, next) {
res.render('<pug file name>', { title: 'Express' });
});
Set your current directory as app root and run the command npm start from your terminal and visit the URL http://localhost:<Port Name>/
Then you can see the rendered .pug file.
Get support for .html file format
Since Express Js supported .pug file format, you need to install ejs node module to get support for the .html format.
npm install ejs --save
Then need to update app.js file content as below
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res, next) {
res.render('<html file name>', { title: 'Express' });
});
Now you will see, .html file is rendered properly.
Add a stylessheet to express app
In app.js file, a directory path is already set for static files as shown below.
app.use(express.static(path.join(__dirname, 'public')));
It means that the public folder is set as static file directory.
So, when linking a stylesheet inside head tag, a relative path for stylesheet should be stated as 'stylesheets/style.css.
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" type="text/css" href="stylesheets/style.css">
</head>

VueJS webpack build error SCSS related

I'm having errors when I try to build my VueJS project with the style sheets.
My error when I run "yarn run dev --watch" produces these errors:
c:\wamp\www\DBViewer2>yarn run dev --watch
yarn run v1.6.0
warning package.json: No license field
$ encore dev --progress=true --watch
Running webpack ...
0% compiling
Webpack is watching the files…
95% emitting ERROR Failed to compile with 1 errors 16:00:56
This dependency was not found:
* !!vue-style-loader!css-loader?sourceMap!../node_modules/vue-loader/lib/style-compiler/index?{"optionsId":"0","vue":true,"scoped":false,"sourceMap":true}!scss-loader!../node_modules/vue-loader/lib/selector?type=styles&index=0!./App.vue in ./assets/App.vue
To install it, you can run: npm install --save !!vue-style-loader!css-loader?sourceMap!../node_modules/vue-loader/lib/style-compiler/index?{"optionsId":"0","vue":true,"scoped":false,"sourceMap":true}!scss-loader!../node_modules/vue-loader/lib/selector?type=styles&index=0!./A
I'm not sure what is causing this. It appears it is looking for the files in the wrong location?
Here is my App.vue file:
<template>
<router-view></router-view>
</template>
<script>
export default {
name: 'app'
}
</script>
<style lang="scss-loader">
/* Import Font Awesome Icons Set */
$fa-font-path: 'font-awesome/fonts/';
#import 'font-awesome/scss/font-awesome.scss';
/* Import Simple Line Icons Set */
$simple-line-font-path: 'simple-line-icons/fonts/';
#import 'simple-line-icons/scss/simple-line-icons.scss';
/* Import Bootstrap Vue Styles */
#import 'bootstrap-vue/dist/bootstrap-vue.css';
/*// Import Main styles for this application*/
#import './assets/scss/style';
</style>
Here is my webpack.config.js:
var Encore = require('#symfony/webpack-encore');
Encore
// the project directory where all compiled assets will be stored
.setOutputPath('public_html/build/')
// the public path used by the web server to access the previous directory
.setPublicPath('/build')
// will create public/build/app.js and public/build/app.css
.addEntry('main', './assets/main.js')
.addEntry('vendor', './assets/js/vendor.js')
// allow legacy applications to use $/jQuery as a global variable
.autoProvidejQuery()
// enable source maps during development
.enableSourceMaps(!Encore.isProduction())
// empty the outputPath dir before each build
.cleanupOutputBeforeBuild()
// show OS notifications when builds finish/fail
.enableBuildNotifications()
// create hashed filenames (e.g. app.abc123.css)
// .enableVersioning()
.enableVueLoader()
// allow sass/scss files to be processed
.enableSassLoader()
;
// export the final configuration
module.exports = Encore.getWebpackConfig();
Any suggestions is greatly appreciated. Have spent 2 days now trying different things and research on google. I'm just not familiar enough with symfony/encore and this is my first vuejs project.
In order to be able to use SCSS in a Vue template, you need to declare in the single file component the following style block:
<!-- Those styles are not scoped to that particular component -->
<style lang="scss">...</style>
<!-- Or those styles are scoped to that particular component -->
<style lang="scss" scoped>...</style>
You can even use both in the same file, if needed.
You'll also need to install the correct node dependencies by running:
npm install --dev node-sass sass-loader
This should then work out of the box when used in a project initialized with vue-cli.
However you could need to add this in your webpack 'test' configuration to make lang="scss" work in tests when using vue-loader's ?inject option:
resolveLoader: {
alias: {
'scss-loader': 'sass-loader',
},
},

references to css and javascript from html don't work only on localhost

I am automatically inserting references to css and js files into html head with help of grunt-link-html plugin, but when viewing the page on http://localhost:9000/ files are not found ('Cannot GET'). The styles and scripts are referenced relatively and are showing when viewing the file by double-clicking from harddrive:
<!-- begin:css -->
<link rel="stylesheet" type="text/css" href="../deploy/css/myproject.min.css">
<!-- end:css -->
<!-- begin:js -->
<script src="../deploy/js/myproject.min.js"></script>
<!-- end:js -->
I'm new to Grunt, what am I missing? Thanks for any help
project structure:
MyProject
_build
node_modules
Gruntfile.js
package.json
deploy
css
myproject.min.css
js
myproject.min.js
src
css
myproject.css
js
myproject.js
index.html
extracts from the gruntfile:
express: {
all: {
options: {
port: 9000,
hostname: "0.0.0.0",
bases: ['C:/Users/user1/MyProject/src']
}
}
},
open: {
all: {
path: 'http://localhost:<%= express.all.options.port%>',
app: 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe'
}
},
link_html: {
your_target: {
jsFiles: ['../deploy/js/portfolio.min.js'],
cssFiles: ['../deploy/css/portfolio.min.css'],
targetHtml: ['../src/index.html'],
options: {
cwd: '../deploy'
}
}
}
grunt.registerTask('server', ['connect', 'express', 'open', 'watch']);
The .. at the beginning of the CSS & JS file paths are correct for Grunt if run from _build subdir, but not for the page, because index.html is at the project root directory.
I would move the Grunt stuff from _build to project's root folder and remove the .. from Gruntfile.js, too.
After a Grunt rerun it should work, then.
I am not familiar with these spesific grunt modules, but I am guessing the problem is that you define the "bases" of express.all as your src folder, and not your "myProject" folder.
So when your server wants to serve you files (like your css and js) it only looks in the /src folder, where you dont have a "../deploy/" folder.
Try changing your bases to ['C:/Users/user1/MyProject/deploy'] and your jsFiles and cssFiles, remove the "../deploy", they should now reside in the "/js" and "/css" folders.
Hope this helps :)
Just a thought or two:
1.Try using the same separator in all links, as there is a difference between "\" and "/" in some environnements (browsers vs editor vs os vs anything else).
2. (dumb question ?!) Are you sure you have read/write/execute rights on the files you are accessing ?

Angular2.0 in subdirectory, SystemJS cant import angular components

I am getting started with Angular2.0. I have been following the 5 Min Quickstart and everything works fine although I am using grunt to compile my Typescript and some Sass etc.
I just have one problem I cant solve by myself. I want to move all the public files (generated Javascript and production node modules into a subdirectory. I need to have that, because I run different applications unter the same domian. The frontend depends on the user type that logged in. (backend is written with phalcon)
This is my public folder (the webserver's root)
So the whole Angular applications should live inside the "talent" directory.
The "index.html" contains the following:
<script type="text/javascript" src="/talent/node_modules/systemjs/dist/system.src.js"></script>
<script type="text/javascript" src="/talent/node_modules/angular2/bundles/angular2.dev.js"></script>
<script>
System.config({
baseURL: '/talent',
packages: {'app': {defaultExtension: 'js',}}
});
System.import('app/app');
</script>
SystemJs is able to load my app.js file correctly but then trys to import angular2:
import {bootstrap, Component} from 'angular2/angular2';
Corresponding Javascript:
var angular2_1 = require('angular2/angular2');
This sends a request to http://example.dev/talent/angular2/angular2 resulting in an 404 error.
When I move the node_modules folder and the app folder to the webserver's root and remove baseURL: '/talent' it works just fine.
Here are the requests made for both the working solution (everything at root) and the not working part (everything under /talent)
Working:
Not working:
Can you help me getting this to work?
Had this exact same problem, and just figured it out after several hours. The System config baseURL needs to be set BEFORE angular2.dev.js is loaded. This is because the System.register calls need to be aware of the baseURL at the time of registrations.
e.g.
System.config({ baseURL: '/talent' });
A cleaner way is to just add System.config({ baseURL: '/talent' }) to the very bottom of the system.src.js file.
You can set paths for each library :
System.paths = {
'angular2/*': '/talent/node_modules/angular2/*',
'app/*': '/talent/app/*'
};
Does this work for you?
'angular2/angular2' has been deprecated. Your code should reference 'angular2/core' or the appropriate module for your imports.
You should also not need to specify the path for the angular2 imports in your System.config as System will load them in from the <script> tag you have in the HTML.
You are most likely receiving the 404 error because the angular2.dev.js file is loading 'angular2/core', 'angular2/common', 'angular2/platform/browser', etc... and you are referencing 'angular2/angular2' which is not being registered and therefor SystemJS is attempting to go out and find it.
Change all of your import {...} from 'angular2/angular2' to the correct module import as well. You can find these on the API Preview page of angular.io, or hopefully your IDE will find it for you.
I don't know which version of Angular2 you use but now with beta versions you should use these Angular2 modules:
import {bootstrap} from 'angular2/platform/browser';
import {Component} from 'angular2/core';
Then you need to configure SystemJS as described below:
<script>
System.config({
map: {
app: 'talent/app'
},
packages: {
app: {
format: 'register',
defaultExtension: 'js'
}
}
});
System.import('app/boot')
.then(null, console.error.bind(console));
</script>
With this configuration, when trying to load the app/boot module, SystemJS will load the talent/app/boot.js file that was compiled before from the talent/app/boot.ts file. This behavior applies to all elements under the app module but not to other ones.
Modules like angular2/* will be found from files talent/node_modules/angular2/bundles/[something].js you included using <script> tags.
I made some tests and this configuration works for me ;-)
Thierry
I stumbled upon this question when trying to move from a local (dev) environment to a hosted server (CentOS) where the deployed URLs were all different to my local host. If you're in this situation and the accepted answer doesn't solve your problem (I was already importing the updated imports with Angular2 Beta 15) and using baseURL messes other things up (as it did in my situation) then use:
map: {
app: 'path/to/app/folder'
},
I saw this here and it worked for me (even though it was originally answering a MAMP environment question): Troubles with importing classes from Angular 2 modules with Typescript 1.7
Here's what worked for us:
Make the base ref point to the subdirectory containing the angular project. This will ensure that all the node_module dependencies are found, etc.
Configure the PathLocationStrategy with a different APP_BASE_HREF so that html5 mode still works for the actual angular app.
bootstrap(AppComponent, [..... bind(APP_BASE_HREF).toValue("/yardmap/planning")
ref: https://angular.io/docs/ts/latest/api/common/index/APP_BASE_HREF-let.html
ref: https://angular.io/docs/ts/latest/guide/router.html
base href
Most routing applications should add a element to the index.html as the first child in the tag to tell the router how to compose navigation URLs.
<!DOCTYPE html>
<html>
<head lang="en">
<base href="/talent/">
......
</head>

Resources