Linaria + Next.js + Path Aliases - next.js

I wanted to give Linaria (utilizing next-linaria) a try, but I'm currently stuck to get it working in any of my Next.js projects (that also use Typescript by the way).
The root of evil seems to be path aliases that are supported by Next.js by default.
tsconfig.json
...
"compilerOptions": {
...
"paths": {
"~/*": [
"src/*"
]
}
},
When just installing Linaria and next-linaria, I get an error like this:
Error: Can't resolve '~/layout/main/MainWrapper' in '[...]\src\layout\main'
I already know that Linaria stated to not support any other module aliasing than #babel-plugin-module-resolver or webpack. However, I can't get either of those to work.
I tried #babel-plugin-module-resolver and put same path configuration (and some other tries) to .babelrc without success.
"plugins": [
["module-resolver", {
"alias": {
"~/*": [
"src/*"
]
}
}]
]
I also tried doing the same with webpack aliases.
next.config.js
module.exports = withLinaria({
webpack: (config, { dev }) => {
config.resolve.alias = {
...config.resolve.alias,
"~/": path.resolve(__dirname, "./src/"),
};
return config;
},
});
The default project structure of Next.js looks like this:
/
/pages (contains entry points for each route)
/src (contains regular react components)
So, I'm kindly asking if anyone can tell us how to use path aliasing with Next + Linaria.

Related

How to develop/debug two apps with shared components using vue3 and vite?

I'm building a couple of apps with vue3 and vite, using some shared components. The production build process works OK but I'm having a problem with dev/debug. The Vite docs (for multi-page apps) says
"During dev, simply navigate or link to /nested/ - it works as
expected, just like for a normal static file server."
but I don't know what this means - how do I link to a sub folder? I have added /src/app1 to url in launch.json, but it has no effect. I have also tried using cd src\app1 in the terminal before running npm run dev
"version": "0.2.0",
"configurations": [
{
"type": "firefox",
"request": "launch",
"name": "vuejs: firefox -width 300 -height 600 -P default",
"url": "http://localhost:5173/src/app1",
"webRoot": "${workspaceFolder}",
"pathMappings": [
{
"url": "file:///C:",
"path": "c:"
}
]
}
]
(This launch.json works well with a simple single-page app).
What happens with trying to debug one of the apps is that the project launches but with an empty index.html (i.e. a blank screen with no errors). I'm pretty sure the basic project structure is OK because (as I said) the build process works; I get two separate outputs of html+css+js both of which work as expected, with the correct shared components.
Also, if I tell the Vite server to automatically open the page (as I have done in my vite.config.js below) the page opens correctly - although without a debugger attached of course. So I guess that the settings in launch.json are incorrect.
The project structure is:
-src
-app1
-app.vue
-index.html
-main.js
-app2
-app.vue
-index.html
-main.js
-assets
...
-shared
-components
-shared.vue
If I have just one index.html, moved up a level, I can debug each app but only by editing it every time to point to a different main.js and to change the title, which seems a laborious way of approaching the task.
Below is my vite config. The extra lines in alias were added as an attempt to solve the problem but they are probably incorrect (or unneccesary)
import { fileURLToPath, URL } from 'node:url'
import { resolve } from 'path'
import { defineConfig } from 'vite'
import vue from '#vitejs/plugin-vue'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
server: {
base: '/src/app1',
open: '/src/app1/index.html',
},
resolve: {
alias: {
vue: 'vue/dist/vue.esm-bundler.js',
'#': fileURLToPath(new URL('./src', import.meta.url)),
app1: fileURLToPath(new URL('./src/app1', import.meta.url)),
app2: fileURLToPath(new URL('./src/app2', import.meta.url)),
// shared: fileURLToPath(new URL('./src/shared/components', import.meta.url)),
}
},
build: {
rollupOptions: {
input: {
app1: resolve(__dirname, './src/app1/index.html'),
app2: resolve(__dirname, './src/app2/index.html'),
},
},
},
})
I've made things more complex than neccesary because I missed the important setting. In vite.config.js, it's important to define root to point to where each index.html is found. So for my structure above, the config file looks like
import { defineConfig } from 'vite'
import vue from '#vitejs/plugin-vue'
export default defineConfig({
plugins: [vue() ],
root: "src\app1",
resolve: {
alias: {
vue: 'vue/dist/vue.esm-bundler.js',
}
}
})
In the process I've also swapped from Firefox to Chrome for debug (I was getting a lot of irrelevant error messages from Firefox), and my launch.json is now simply
{
"version": "0.2.0",
"configurations": [
{
"type": "chrome",
"request": "launch",
"name": "Launch Chrome against localhost",
"url": "http://localhost:5173",
"webRoot": "${workspaceFolder}",
}
]
}
It doesn't really matter what the file structure looks like, as long as within each file its dependencies are correctly addressed. The only important bit is the root. Simply by changing that from 'app1' to 'app2' will switch both the debug and the build to the correct folders, with the release (built) files being stored in subfolders of 'app1' and 'app2' independently.
It would be easy to extend this to have more than 2 apps each sharing the same common components.

How do I make Next deal with regular CSS files in addition to SCSS files?

Right now, I have a Next config file that looks like this:
const withSass = require('#zeit/next-sass')
module.exports = withSass({
cssModules: true,
webpack: config => {
config.module.rules.push({
test: /\.svg$/,
use: [
{
loader: 'babel-loader'
},
{
loader: 'react-svg-loader',
options: {
jsx: true // true outputs JSX tags
}
}
]
})
config.plugins = config.plugins || []
return config
}
})
And using SCSS modules works just fine. But, I am adding in Reach UI's #reach/dialog, which requires you to include their styles.css file, and I get this error when I do:
./node_modules/#reach/dialog/styles.css 4:0
Module parse failed: Unexpected token (4:0)
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
|
| /* Used to detect in JavaScript if apps have loaded styles or not. */
> :root {
| --reach-dialog: 1;
| }
How do I configure my app to deal with this, while keeping the SCSS working? Do I have to install next-css in addition to next-sass? How do I use both, if so? Is something else going on that I'm missing?

Why does there appear to be non deterministic behavior trying to load a babel plugin in a nextjs project? Next - Babel

I have a nextjs app with redux.
When I try to use the ?? operator in my pages/index, it works as it should.
I then tried to load up a redux store with a bunch of reducers. When I hit the ?? in a reducer file, I get this error:
Support for the experimental syntax 'optionalChaining' isn't currently enabled (71:32):
I also get the error in any other file: component, actions and reducers. It is only directly in the pages/* that the plugin is working properly.
My app is using next#9.1.1 and redux#4.0.4. Here is my .babelrc file:
"env": {
"development": {
"presets": ["next/babel"],
"plugins": [
"#babel/plugin-proposal-optional-chaining",
"#babel/plugin-proposal-nullish-coalescing-operator",
[
"styled-components",
{ "ssr": true, "displayName": true, "preprocess": false }
]
]
}
}
}
Is there something that would override my babel config for certain files? If so, what am I missing? What else should I look at?

Making sure vendor JS is called before custom JS (WordPress Sage)

I can't find how to make vendor scripts load before my own scripts. In manifest.json I tried:
"dependencies": {
"main.js": {
"files": [
"scripts/vendor_script.js",
"scripts/custom_script.js"
],
"main": true
},
Doesn't work: vendor script is called after my custom script. Also tried:
"dependencies": {
"plugins.js": {
"files": [
"scripts/vendor/owl.carousel.min.js"
]
},
"main.js": {
"files": [
"scripts/main.js"
],
"main": true
},
Same. Any suggestion?
[EDIT] my current manifest.json file, where I followed the advice from https://discourse.roots.io/t/custom-javascript-in-manifest-json-and-building-out-into-a-single-file/3316:
{
"dependencies": {
"main.js": {
"vendor": [
"scripts/vendor/owl.carousel.min.js"
],
"files": [
"scripts/main.js"
],
"main": true
},
"main.css": {
"files": [
"styles/main.scss",
"styles/vendor/font-awesome.min.css",
"styles/vendor/owl.carousel.min.css"
],
"main": true
},
"customizer.js": {
"files": [
"scripts/customizer.js"
]
},
"jquery.js": {
"bower": ["jquery"]
}
},
"config": {
"devUrl": "http://127.0.0.1/pot/"
}
}
[EDIT #2]
$ node
> require('asset-builder')('./assets/manifest.json').globs.js
require('asset-builder')('./assets/manifest.json').globs.js
[ { type: 'js',
name: 'main.js',
globs:
[ 'D:\\EasyPHP\\www\\pot\\wp-content\\themes\\pot\\bower_components\\bootstrap-sass\\assets\\javascripts\\bootstrap\\transition.js',
'D:\\EasyPHP\\www\\pot\\wp-content\\themes\\pot\\bower_components\\bootstrap-sass\\assets\\javascripts\\bootstrap\\alert.js',
'D:\\EasyPHP\\www\\pot\\wp-content\\themes\\pot\\bower_components\\bootstrap-sass\\assets\\javascripts\\bootstrap\\button.js',
'D:\\EasyPHP\\www\\pot\\wp-content\\themes\\pot\\bower_components\\bootstrap-sass\\assets\\javascripts\\bootstrap\\carousel.js',
'D:\\EasyPHP\\www\\pot\\wp-content\\themes\\pot\\bower_components\\bootstrap-sass\\assets\\javascripts\\bootstrap\\collapse.js',
'D:\\EasyPHP\\www\\pot\\wp-content\\themes\\pot\\bower_components\\bootstrap-sass\\assets\\javascripts\\bootstrap\\dropdown.js',
'D:\\EasyPHP\\www\\pot\\wp-content\\themes\\pot\\bower_components\\bootstrap-sass\\assets\\javascripts\\bootstrap\\modal.js',
'D:\\EasyPHP\\www\\pot\\wp-content\\themes\\pot\\bower_components\\bootstrap-sass\\assets\\javascripts\\bootstrap\\tooltip.js',
'D:\\EasyPHP\\www\\pot\\wp-content\\themes\\pot\\bower_components\\bootstrap-sass\\assets\\javascripts\\bootstrap\\popover.js',
'D:\\EasyPHP\\www\\pot\\wp-content\\themes\\pot\\bower_components\\bootstrap-sass\\assets\\javascripts\\bootstrap\\scrollspy.js',
'D:\\EasyPHP\\www\\pot\\wp-content\\themes\\pot\\bower_components\\bootstrap-sass\\assets\\javascripts\\bootstrap\\tab.js',
'D:\\EasyPHP\\www\\pot\\wp-content\\themes\\pot\\bower_components\\bootstrap-sass\\assets\\javascripts\\bootstrap\\affix.js',
'scripts/vendor/owl.carousel.min.js',
'assets/scripts/main.js' ] },
{ type: 'js',
name: 'customizer.js',
globs: [ 'assets/scripts/customizer.js' ] },
{ type: 'js',
name: 'jquery.js',
globs: [ 'D:\\EasyPHP\\www\\pot\\wp-content\\themes\\pot\\bower_components\\jquery\\dist\\jquery.js' ] } ]
The script I'm trying to use is Owl Carousel. If I add the following in head.php it works fine:
<script src="<?php bloginfo("template_url"); ?>/assets/scripts/vendor/owl.carousel.min.js" type="text/javascript" charset="utf-8"></script>
If, instead, I set my manifest.json as shown previously I get a ".owlCarousel is not a function" in Firebug and my slider doesn't work.
Note: I didn't use Bowel, it's not mandatory in regular Sage workflow right? I just copied owl.carousel.min.js into assets/scripts/vendor/.
On a fresh Sage 8 installation I was able to quickly install OwlCarousel using Bower, exactly as described in the Sage documentation without any issue; its script and styles were both correctly included before project scripts and styles.
Font Awesome requires a Bower override because its default Bower main property instructs Bower to use a LESS and a SCSS file; once I set it to just use SCSS it worked fine. Sage 8 ships with a working set of Bower overrides which you should use as an example. See here.
Something else is going wrong with your scripts or your asset builder setup if you're unable to manually add scripts in the correct order. I suspect your asset paths may be incorrect. The best way to troubleshoot and ensure your manifest points to the correct asset paths is to start an interactive node session in a new terminal window.
First run (in your theme dir):
node
Then run (also in your theme dir):
require('asset-builder')('./assets/manifest.json').globs.js
or (still in your theme dir):
require('asset-builder')('./assets/manifest.json').globs.css
The output will display both the assets' paths and the order they're being included.
If you modify manifest.json while running the gulp watch task it may be necessary to halt the task, run a default gulp build, and then restart your gulp watch task.
If you still have difficulty after viewing the asset-builder output using the steps above then please post (either here or on the Roots forum) the output here along with the installation steps you took when installing the vendor scripts and custom scripts you're attempting to use so that someone can attempt to recreate your environment.

With Webpack, is it possible to generate CSS only, excluding the output.js?

I'm using Webpack with the extract-text-webpack-plugin.
In my project, I have some build scripts. One of the build scripts is supposed to bundle and minify CSS only. As I'm using Webpack for the other scripts, I found it a good idea to use Webpack even when I only want to bundle and minify CSS.
It's working fine, except that I can't get rid of the output.js file. I don't want the resulting webpack output file. I just want the CSS for this particular script.
Is there a way to get rid of the resulting JS? If not, do you suggest any other tool specific for handling CSS? Thanks.
There is an easy way, no extra tool is required.
There is an easy way and you don't need extra libraries except which you are already using: webpack with the extract-text-webpack-plugin.
In short:
Make the output js and css file have identical name, then the css file will override js file.
A real example (webpack 2.x):
import path from 'path'
import ExtractTextPlugin from 'extract-text-webpack-plugin'
const config = {
target: 'web',
entry: {
'one': './src/one.css',
'two': './src/two.css'
},
output: {
path: path.join(__dirname, './dist/'),
filename: '[name].css' // output js file name is identical to css file name
},
module: {
rules: [
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: 'css-loader'
})
}
]
},
plugins: [
new ExtractTextPlugin('[name].css') // css file will override generated js file
]
}
Unfortunately, that is currently not possible by design. webpack started as a JavaScript bundler which is capable of handling other "web modules", such as CSS and HTML. JavaScript is chosen as base language, because it can host all the other languages simply as strings. The extract-text-webpack-plugin is just extracting these strings as standalone file (thus the name).
You're probably better off with PostCSS which provides various plugins to post-process CSS effectively.
One solution is to execute webpack with the Node API and control the output with the memory-fs option. Just tell it to ignore the resulting js-file. Set the output.path to "/" in webpackConfig.
var compiler = webpack(webpackConfig);
var mfs = new MemoryFS();
compiler.outputFileSystem = mfs;
compiler.run(function(err, stats) {
if(stats.hasErrors()) { throw(stats.toString()); }
mfs.readdirSync("/").forEach(function (f) {
if(f === ("app.js")) { return; } // ignore js-file
fs.writeFileSync(destination + f, mfs.readFileSync("/" + f));
})
});
You can clean up your dist folder for any unwanted assets after the done is triggered. This can be easily achieved with the event-hooks-webpack-plugin
//
plugins: [
new EventHooksPlugin({
'done': () => {
// delete unwanted assets
}
})
]
Good Luck...

Resources