I want load minify js file by RequieJs - requirejs

We want to load module using RequireJs.
By the way, the test server should load 'tab.js',
and the real server should load 'tab.min.js'.
We use RequireJS in the Multiple Page Application.
We are using it like "require('tab', function () { ... });" in html files.
So it is difficult to change the name of the loaded module.
// test server
require('tab', function (Tab){ ... } // => load tab.js
// real server
require('tab', function (Tab){ ... } // => load tab.min.js
Is there any way to make this possible?

Use two RequireJS configurations:
For the test server, set the configuration so that tab.js is loaded. How you'd do this depends on specifics you don't provide in your question. A generic way to do it would be to have a paths setting like:
paths: {
tab: "path/to/tab",
}
Remember not to put the .js extension in the path you provide.
For the production server (i.e. the "real" server), set the configuration so that tab.min.js is loaded. The example above would be modified to:
paths: {
tab: "path/to/tab.min",
}

Related

How to use ReactDOMServer.renderToStaticMarkup without nodejs server

I want to use ReactDOMServer.renderToStaticMarkup to create a static website, but I only want to generate the html string once during build instead of dynamically for every request
Here are the relevant docs, but they don't go into much detail on implementation https://reactjs.org/docs/react-dom-server.html#rendertostaticmarkup
What is the best practice for using react to generate html one time during build instead of dynamically on every page request? I am using webpack.
For anyone who comes here looking for answers, here's how I did it:
Create a separate webpack config file for your SSR react like webpack.ssr.js. This file will have the same config you'd normally have for react SSR.
In the index.js file where you'd usually have ReactDOM.render, run the ReactDOMServer.renderToStaticMarkup function.
In the index.js file, write the html string to a file:
const html = ReactDOMServer.renderToStaticMarkup(App);
fs.writeFile("index.html", html, (err) => {
if (err)
console.log(err);
else {
console.log("File written successfully\n");
}
});
After every build, execute the build file as a node script. For example node build.js. I'd recommend doing this in package.json as a postbuild script. For example:
postbuild: "node build.js"
The fs.writeFile will update the index.html file each time you build, so you'll just need to serve index.html like you would with any other static website.
For css modules, you'd use something like isomorphic-style-loader instead of the regular style-loader.
If you are using something like react-router, you'll need to iterate through all your routes and run ReactDOMServer.renderToStaticMarkup and fs.writeFile for every route. Then you'd serve the different html files with server side routing.
This will also work for normal SSR using ReactDOMServer.renderToString, especially if you don't need dynamic SSR based on something like an ID. For generating the loading screen server side, this is great and there's really no reason to generate html dynamically at runtime.

Controller reference is not defined node.js application

I'm working on a node.js single-page web application where I wanna use MVC. On my back-end, i'm using postgres database to store data that will be provided by the user throught forms interaction. For this, i'm also using Sequelize.
When 'npm start' runs, the application verifies if the database already exists locally, if not, then it is created with its tables and relations, just as expected.
On my front-end, the application loads a file called index.html (where all forms will be located). In this file, I'm trying to use my controllers to call 'create' methods using Sequelize, but i can't exacly call those functions on html script tag.
The first errors i was getting was 'required is not defined' when I was trying to do things like 'var PropController = require('../controllers/PropriedadeController.js')'. After some research, just figured out that it has somethings to do with browser/client-side in JavaScript.
I'm now trying to deal with this using Browserify, but still can't find out how it fits in my case. I did some research, but couldn't find a similar situation.
Basically, my idea is to reference all my controllers in a script.js file, and then browserify this file, in order to use it in my html file in the script tag.
My controller file:
const models = require("../models")
exports.findCreate = obj => {
return new Promise((resolve, reject) => {
models.Produtores.findOrCreate({
attributes: ["propt_nomeProdutor"],
where: { propt_nomeProdutor: obj.propt_nomeProdutor },
defaults: {
propt_nomeProdutor: obj.propt_nomeProdutor
}
})
.then(resp => {
resolve(resp);
})
.catch(e => {
reject(e);
});
});
};
My script.js file:
const ProdController = require("./ProdutorController");
module.exports = ProdController
And in my index.html file, after running 'browserify script.js -o bundle.js', i'm calling this generated script. So now, Inside a script tag, i'm trying to:
`(html form here)
<script src="../controllers/bundle.js"></script>
</body>
</html>
<script>
// ProdController.findCreate(obj) ...
</script>`
After trying this, i'm getting an error 'ProdController is not defined'. I even tried to browserify my controller file and my script.js into the bundle.js file, but then i'm getting an error witch I couldn't solve either:
Uncaught Error: Cannot find module './dialects/postgres/data-types'
I would like to know if there is any solution for this. I'm afraid that it's not possible to do this using these dependencies all together. I did a similar application using Electron, but now i'm trying to deal with a browser, and can't figure out how to do it.
This project is in my github repo: https://github.com/gabrielftwgarcia/TCC2
Any help will be greatly appreciated.
I think you are not familiar with front-end and back-end concepts. Controller is used at back-end side and it cannot use at front-end side. If you want to call a controller method you should write a new router to execute that method.
And another important thing is require method belongs to Node scripts and cannot be used at front-side.

Set Base URL for Preact CLI

Using Preact CLI is it possible to set the path where the app will be hosted outside of the root directory?
For instance hosting the app at http://mywebsite.com/relativepath/index.html
You have several problems to solve:
1. Get Webpack to output the correct paths in your html
This is done via creating a preact.config.js in your root folder, and put the following in there
export default (config) => {
config.output.publicPath = '/relativepath/';
};
2. Set your navigation and assets links in your app
The best way to solve it in my opinion is to use a global variable which you can be used in your app. So again, edit the preact.config.js to the following:
export default (config, env, helpers) => {
config.output.publicPath = '/relativepath/';
// use the public path in your app as 'process.env.PUBLIC_PATH'
config.plugins.push(
new helpers.webpack.DefinePlugin({
'process.env.PUBLIC_PATH': JSON.stringify(config.output.publicPath || '/')
})
);
};
3. Routing
When using your preact app, it should be no problem to navigate. However, if you try to load a fresh URL e.g. www.myserver.com/relativepath/mything/9, the server doesn't know that it should load your single page app living at www.myserver.com/relativepath/index.html
You have two options:
a) Server-side routing
Make sure your all the requests to relativepath (including e.g. relativepath/mything/9) will be rewritten to your app's relativepath/index.html (in case of using Apache).
Then your Javascript can process the routes, e.g. preact-router
b) Client-side routing (recommended)
The easier option for enabling reloading of URLs is to use hash urls, thereby avoid going through the server when loading a URL.
Your URLs will look something like www.myserver.com/relativepath/#/mything/9
The server ignores the part after # and only loads (hopefully) /relativepath/index.html
You can use e.g. the preact-router with Hash History to avoid server-side routing, read about it here https://github.com/developit/preact-router#custom-history
I'm proxying from http-proxy-middleware to the preact-cli dev server and these settings worked for me in preact.config.js
export default (config, env, helpers) => {
config.output.publicPath = '/relativepath';
config.devServer.devMiddleware.publicPath = "/relativepath";
};

Location of Mirage files in ember addon

I have an Ember addon which is supposed to handle a request to return some data. The main app needs to use this addon, so that requests to retrieve this data are retrieved from mirage. At some point in the future this needs to be disabled in live environments (but not for the time being)
My question is where the mirage directory (and its subdirectories such as factories, fixtures, models, routes etc) should be located in an addon. Should it be in the project root or elsewhere, such as in the app or addon subdirectory?
I have run:
ember install ember-cli-mirage
which creates some files in \tests\dummy\mirage
Creating the files in this directory doesn't seem to work:
/tests/dummy/fixtures/mydata.js
export default [{
"title": "Some data here"
}]
/tests/dummy/routes/mydata.js
class MyDataRoutes {
constructor(routerFnc, route, db) {
routerFnc(route + '/', ({db}) => {
return db.mydata;
});
}
}
export default MyDataRoutes;
/tests/mirage/config.js:
export default function() {
// this.urlPrefix = ''; // make this `http://localhost:8080`, for example, if your API is on a different server
this.namespace = 'api'; // make this `api`, for example, if your API is namespaced
this.timing = 100; // delay for each request, automatically set to 0 during testing
new MyDataRoutes(this.get, '/content/mydata', this.db);
}
This is the right place.
You will then be able to use your mirage endpoints either in your tests or in the dummy app directly.
If you want an example of how that would all work together, you can have a look at the repo for ember-power-select https://github.com/cibernox/ember-power-select. They have mirage as well as nice tests in place.

Can I use webpack on the client side without nodejs server?

I am trying to build a web app where I want to store all html, js and css files on amazon s3, and communicate with a restful server through api.
I am trying to achieve lazy loading and maybe routing with react router. It seems that webpack has this feature code splitting that would work similarly as lazy loading.
However, all of the tutorial and examples I found involves webpack-dev-server, which is a small node express server. Is there anyway I could generate bundle at build time and upload everything to amazon s3 and achieve something similar to Angular's ocLazyLoading?
It's definitely possible to create a static bundle js file, which you can use in your production code that does not include webpack-dev-server.
See this example as a reference (note: I am the owner of this repo). webpack.prod.config.js does create a production ready bundle file using webpack via node.js which itself does not require node.js anymore. Because of that you can simply serve it as a simple static file (which is done in the live example).
The key difference is how the entry points are written in the dev- and production environments. For development webpack-dev-server is being used
module.exports = {
entry: [
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server',
'./src/index'
],
// ...
}
In the production environment you skip the webpack-dev-server and the hot reloading part
module.exports = {
entry: [
'./src/index'
],
// ...
}
If you want to split your code into more than one bundle, you might want to have a look at how to define multiple entry points and link the files accordingly.

Resources