set NODE_PATH in netlify dev - absolute imports - environment-variables

Hi how can I set NODE_PATH like in .env file for a netlify dev. Because I got an errors
Module not found: Can't resolve 'index.css' in '/mnt/y/projects/instagram-story-saver/src'
App is built on Create React App

.env file does not work, but newer method does work:
in jsconfig.json:
{
"compilerOptions": {
"baseUrl": "src"
},
"include": ["src"]
}

Related

Rollup configuring alias for semantic-ui-less #import

I have been configuring rollup for creating custom react component library on top of fomantic-ui.
I have already setup the rollup.config.js
ALthough in the configuration, I need to resolve an import:
#import (multiple) '../../theme.config';
the import is part of fomantic-ui-less library, which needs to be resovled to:
path.join(__dirname, '/themes/theme.config')
and I do have themes/theme.config at my project root.
when I run build command it throws following error:
[!] (plugin postcss) Error: '../../theme.config' wasn't found. Tried - E:\Projects\UILibrary\node_modules\fomantic-ui-less\theme.config,..\..\theme.config
and I have used the rollup-plugin-postcss plugin and #rollup/plugin-alias, and called it inside plugins array
...
plugins: [
...
alias({
entries: [
find: '../../theme.config$',
replacement: path.join(__dirname, '/themes/theme.config')
]
})
postcss(),
...
]
I have also tried changing the order of plugins.
And the worst part is, it is working when configuring the storybook, using webpack alias.
.storybook/main.js
webpackFinal: async (config) => {
config.resolve.alias = {
"../../theme.config$": path.join(__dirname, "../themes/theme.config")
}
...
}

Gatsby .env.production variables - undefined

When building a Gatsby project I'm getting all env variables undefined in production environment.
In development everything is fine.
I have 2 similar .env.development and .env.production files.
In my gatsby-config.js I have
require('dotenv').config({
path: `.env.${process.env.NODE_ENV}`,
});
and if I console.log(process.env.NODE_ENV) during gatsby build it gives production and the variables can be accessed and logged out.
But later in code something like
return request.post(`${process.env.GEOCODING_CF_URL}/latlng`, {...});
gives request to http://localhost:9000/ru/undefined/latlng.
What am I doing wrong and how this issue can be fixed?
UPDATE:
When I run gatsby build - process.env.NODE_ENV is production
When I run gatsby serve - process.env.NODE_ENV is undefined
If this can help in any way.
If you use environment variables in node you don't need a prefix (like in your gatsby-config.js). However, if you need to use them in a component or a page you must add GATSBY_ as a prefix, so GEOCODING_CF_URL should be GATSBY_GEOCODING_CF_URL
For me, NODE_ENV=production yarn gatsby serve did the trick.
https://www.gatsbyjs.com/docs/how-to/local-development/environment-variables/
Accessing Environment Variables in the browser.
By default, environment variables are only available in Node.js code and are not available in the browser as some variables should be kept secret and not exposed to anyone visiting the site.
To expose a variable in the browser, you must preface its name with GATSBY_. So GATSBY_API_URL will be available in browser code but API_KEY will not.
Variables are set when JavaScript is compiled so when the development server is started or you build your site.
src/pages/index.js
Copysrc/pages/index.js: copy code to clipboard
import React, { useState, useEffect } from "react"
function App() {
const [data, setData] = useState()
useEffect(async () => {
const result = await fetch(
`${process.env.GATSBY_API_URL}/users`
).then(res => res.json())
setData(result.data)
})
return (
<ul>
{data.map(user => (
<li key={user.id}>
<a href={user.url}>{user.name}</a>
</li>
))}
</ul>
)
}
export default App

Electron app with Nex.js (loading html files not working)

I'm building an electron app using Next.js and electron-next package so Electron can handle the "ouput" folder from Next.js.
The app works great (simple html "hello world" test for all) for development; however, when I'm packaging the app with electron-builder, the page doesn't load and the DevTools is saying that it cannot load local files. I can see the files generated by electron-builder and nowhere I can find the static html files. Is there something I'm missing? Are the static files are included in the *.asar file?
This is for Electron under Windows 10.
Below I'm showing the package.json file setup for electron-builder, as well as the call to open the initial HTML file on the app entry file (index.js)
// ---------package.json----------
"scripts": {
"start": "electron .",
"build": "next build renderer && next export renderer",
"dist": "npm run build && electron-builder"
},
"build": {
"files": [
"**/*",
"renderer"
]
},
// --------index.js----------
// I can confirm that /renderer/out/start.html file is created
const devPath = "http://localhost:8000/start"
const prodPath = path.resolve('renderer/out/start.html')
const entry = isDev ? devPath : ('file://' + prodPath)
console.log(entry)
win.loadURL(entry)
This is the error I get:
Not allowed to load local resource: file:///C:/Users//Desktop/text_exc_app/dist/win-unpacked/resources/renderer/out/start.html
I found from another post that you can also do this (using app.getAppPath()):
const prodPath = path.join(app.getAppPath() ,'renderer/out/start.html')
This solved my problem!
I'm still not sure as to what is the difference between the two ways of accessing the files is, and why one works and the other one doesn't.

How do I set NODE_ENV=production on Electron app when packaged with electron-packager?

How do I make packaged releases of my Electron application set NODE_ENV=production when packaged with electron-packager?
UPDATE 2019/12
Use app.isPackaged: https://electronjs.org/docs/api/app#appispackaged-readonly
It returns true if the app is packaged, false otherwise. Assuming you only need a check if it's in production or not, that should do it. The env file solution detailed below would be more suitable if you had different environments/builds with different behaviors.
To my knowledge, you can't pass env vars to a packaged electron app on start (unless you want your users to always start it from the command line and pass it themselves). You can always set that env variable in your application like this: process.env.NODE_ENV = 'production'. You could integrate that with electron-packager by having an env file that gets set in your build and is required by your application to determine what environment it's in.
For example, have a packaging script that looks like:
"package": "cp env-prod.json src/env.json && npm run build"
and in your src/main.js file:
const appEnv = require('./env.json');
console.log(appEnv) //=> { env: "prod", stuff: "hey" }
//you don't really need this, but just in case you're really tied to that NODE_ENV var
if(appEnv.env === 'prod') {
process.env.NODE_ENV = 'production';
}
You can set it in 2 ways.
By command line with --no-prune see here in the usage guide
Or programmatically with this API
var packager = require('electron-packager');
var options = {
'arch': 'ia32',
'platform': 'win32',
'dir': './'
'prune': true //this set the enviroment on production and ignore dev modules
};
packager(options, function done_callback (err, appPaths) { /* … */ })
For more options see this guide

how to deploy your dart app (using Web ui) without using Pub Deploy

What is the best strategy to deploy a Dart Web-ui app manually ?
pub deploy doesn't work for me and I have raised bug report. So am thinking what is the best way to manually deploy.
This is how I started:
1) From project root I compile the webui components (dwc.dart)
2) change directory to web/out then run dart2js
3) copy all .js files into that scripts/js public folder on server
4) copy appname.html to server changing css and script paths to option 3
5) Make sure dart.js is also in the same directory as item 3
this is as far as I got. So what else do I need to do ?
A few questions:
1) Do I manually change the file paths in the generated .js files to point to public folders on server for the files they are referencing and make sure those files are on server also ?
2) Do I need to copy all packages to server also ?
3) Any preferred file structure on server?
Any tips on this really appreciated.
Thanks.
I wrote a Grunt script for it (since I had no time to look up how to properly write code for Grunt, I did not share the code since it's a mess) but I basically do this:
compiling a list of files with dwc to a given out dir
compile it to javascript
clean up all non-deployable files
change some paths inside the HTML to match the server paths (for some reasons, this gets changed by the compilation process)
remove all packages except the ones I really need (JS interopt and browser)
Since I'm only using the JS version, I remove all dart packages. Since the paths inside the HTML files are up to you, you can already use a structure that suits you/your server.
I can provide you with a Grunt script to understand the order of tasks. Practically the order I use is this one:
Create the build directory. I usually use /build/web. I usually create these files (index.html, main.dart, /css and so on into the /web dir). I create the rest of components into /lib directory.
Compile the .dart file that contains the main() function ("main.dart" in my case for simpler projects) file to Javascript and put it into /build/web directory
Copy the other needed files and folders to the /build/web directory. Also, during this process you'll be copying the packages that your project needs. You'll see in the example provided below.
Remove all empty folders from the project
You can create a Grunt task to open the /index.html file in the browser once the building process has ended (I will not provide this example)
The structure of the dart test project:
testApp
- gruntfile.js
- package.js
/lib
/packages
/angular
/web
- index.html
- main.dart
/css
/img
So, the Grunt example script to cover steps from 1 - 4 looks like this (copy it to gruntfile.js):
module.exports = function (grunt) {
grunt.initConfig({
// 1.
// create build web directory
mkdir: {
build: {
options: {
create: ['build/web']
}
}
},
// 2.
// compile dart files
dart2js: {
options: {
// use this to fix a problem into dart2js node module. The module calls dart2js not dart2js.bat.
// this is needed for Windows. So use the path to your dart2js.bat file
"dart2js_bin": "C:/dart/dart-sdk/bin/dart2js.bat"
},
compile: {
files: {'build/web/main.dart.js': 'web/main.dart'}
}
},
// 3.
// copy all needed files, including all needed packages
// except the .dart files.
copy: {
build: {
files: [
{
expand: true,
src: [
'web/!(*.dart)',
'web/css/*.css',
'web/res/*.svg',
'web/packages/angular/**/!(*.dart)',
'web/packages/browser/**/!(*.dart)'
],
dest: 'build'
}
]
}
},
// 4.
// remove empty directories copied using the previous task
cleanempty: {
build: {
options: {
files: false
},
src: ['build/web/packages/**/*']
}
},
});
require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);
grunt.registerTask('default', [
'mkdir:build',
'dart2js',
'copy:build',
'cleanempty:build'
]);
};
So this is the Grunt script example.
Create a /gruntfile.js file into your project's root directory and copy/paste the script to it.
Create a /package.json file into your project's root directory and copy/paste the following script:
{
"name": "testApp",
"version": "0.0.1",
"description": "SomeDescriptionForTheTestApp",
"main": "",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "YourName",
"peerDependencies": {
"grunt-cli": "^0.1.13"
},
"devDependencies": {
"grunt": "^0.4.5",
"grunt-cleanempty": "^1.0.3",
"grunt-contrib-copy": "^0.7.0",
"grunt-dart2js": "0.0.5",
"grunt-mkdir": "^0.1.2",
"matchdep": "^0.3.0"
}
}
Open Command Prompt in Windows, Terminal in Linux, navigate to your project's root directory and use this command:
npm install
Wait untill all Grunt modules needed will be downloaded to your local project. Once this is finished, issue this command in Command Prompt or Terminal:
node -e "require('grunt').cli()"
You can use this to initiate Grunt default task without having Grunt installed globally on your system.
Now, to know the exact build structure for your project (including the packages that the project needs), make a build using Pub Build. Then you will be able to instruct Grunt to create the same dir structure.
You can add other tasks (like minification) if you want.
Hope this will help you all to understand the process and get you started with a test app first. Add your comments to make this even better and simplify it even more.

Resources