is it possible to have multiple modules defined in tsconfig? - node.js

Ok, so I'm making a angular2 app with a node server. I've followed the 5min tutorial so I'm using "system" as the module system. However I am using a simple node express server instead of the way they have in the tutorial. I am writing this in typescript as well, but it is also compiled to "system" style of importing modules. And when running the server I get System is not defined.
How do I fix so System is defined when starting the server?
Is it not recommended to use "system" as the compiler option "module" in the tsconfig-file, when writing a node server?
Can I compile the server code with eg "commonjs" and the angular front end with "system"?
How do I do the configuration of module loading (the small script they have in the index.html) if I would not use "system" in the front end either?

I would recommend to split front-end and back-end applications into different projects and make them communicate through a REST service. I mean the server application will provide the service and the front application will consume it using AJAX.
This way you will be sure that there won't be conflict between the tools you use. For example the use or not of SystemJS. You'll be free to use SystemJS in the Angular2 application as described in the 5min tutorial of the angular.io website and commonjs for the Node / Express application.
The following article describes how to do that:
Angular2 TypeScript Gulp and ExpressJS - http://blog.edenmsg.com/angular2-typescript-gulp-and-expressjs/

As #Thierry Templier suggested, you need to split your code into /client and /server to be more maintainable and structured, if you didn't do that yet.
You can create two tsconfig.json files, put one into /server and other into /client folder.
/server
tsconfig.json ( with module: commonjs )
/client
tsconfig.json ( with module: systemjs )
When you are invoking tsc from shell, you use --project command:
tsc -p ./server <-- /server/tsconfig.json is loaded
tsc -p ./client <-- /client/tsconfig.json is loaded

Related

How to run a node app after production build by WebPack when output is index.html?

***Updated for further clarification:
Thanks much for taking the time to reply. Running 'npm run build' (I'm using the Vuetify/Webpack template) created an index.html and a directory named 'static' with the respective html, css, and js (in 'dist' directory). The question is - how can I run this in production using node or pm2 (for example, 'pm2 start myapp.js')?
Doing some further research and testing, the 'npm run build' built as static. It was my lack of understanding how vue-cli was to build for production (via WebPack) (vue-cli builds static meant to be served via web server). Doing further testing, I can load and bring up my app on a couple local Linux servers (the static content running on one servers, while MongoDB and API running on another server (API running with pm2)). Also, I was able to bring it up on AWS S3 (as static). I think I have my answer now. Thanks much for your time.
***From Original Post:
How to run the following node app in production? Webpack build produced an index.html (I assume as it's using html-webpack-plugin). I can view the site if I run under a web server (e.g., nginx), but I want to run my final app using pm2, or running node process.
I am using the Vuetify WebPack template (I'm using Vue.js), when I run the npm run build for production (in package.json: “build”: “node build/build.js”) the output is as follows:
$ ls
index.html static/
and
$ ls static/js/
app.f7301c212bc5fefd6563.js manifest.2ae2e69a05c33dfc65f8.js vendor.1aae36aa0dc798d4d36d.js
app.f7301c212bc5fefd6563.js.map manifest.2ae2e69a05c33dfc65f8.js.map vendor.1aae36aa0dc798d4d36d.js.map
So, how do I run this via node (npm start) or pm2 (pm2 start) (can't use index.html or static/js files).
When I run the webpack build I was expecting a .js output (for example ‘build.js’) to run via node or pm2 (npm start that runs ‘node build.js’ or pm2 start build.js). I suppose this will work for serverless, but was looking to run via pm2 (with nginx as proxy) as the app will have other factors (e.g., MongoDB) that won’t allow running in serverless (e.g., AWS Lambda).
Would this be a matter of just re-configuring WebPack to output to a .js file (for example, build.js), or will the static files (served via a webserver, nginx/Apache/http-server) allow for the same functionality? That is, will there be any factors that would limit my app by running as static verses via ‘node build.js’ or ‘pm2 start build.js’, (for example, will my API connects to the back-end still work (back-end being node/JS))?

vue files without NodeJS?

I want to host my app outside of node JS, but I want to use .vue files and possible npm as build system (if it's needed). Is it's possible to do?
I do not need any backward compatibility and if it work on latest Chrome dev it's ok for me.
Is there any examples how it can be done?
I tried to build some webpack template, but it's work only inside NodeJS. On other server I am getting 404 when I am accessing to URLs that placed in .vue files. It's seems that they can't be handled by the other server.
VueJS app is not NodeJS app.
VueJS app is interpreted by the browser.
You just have to build your app on computer and host files as any static website, so any server can serve html and files.
To build your app use e.g. Webpack (https://github.com/vuejs-templates/webpack )
NodeJs only use to build *.js files in front-end, your WebApp dosen't have to run on Nodejs.
1, You can create a index.html file that requires *.js file when webpack built it.
2, Use Chrome to open your index.html file so you can see it works.
You don't need to use vue-cli or other servers if you only want a static page.
But you have to know how to set your webpack.config.js, you can look that doc https://webpack.js.org/guides/getting-started/
Your starting point is wrong. Vue + node.js can build a complete site. Vue is the front-end framework, node's server language. The two can be used in combination. But not vue must rely on node to use. The two of them can be perfect to achieve the front and back separation of the development model.
In projects that use vue, individuals do not recommend configuring webpack and vue-loader separately. You can directly use vue official scaffolding, vue-cli. Do not have to consider these configurations, automatically configured.
Vue-cli
If you just started learning Vue, here's an entry-level demo. Although it is only a small application, but it covers a lot of knowledge points (vue2.0 + vue-cli + vue-router + vuex + axios + mysql + express + pm2 + webpack), including front-end, back-end, database and other sites Some of the necessary elements, for me, learning great significance, would like to encourage each other!
Vue Demo
Best way to develop Vue app is run dev server, and after all just build static assets. You don't need use vuex files, even better is use static template because you can easily integrate it with some back-end (WordPress or whatever).
Helpfully will be use some starter, for ex. Vue.js starter
It's true that vue will create static html pages when you run the build script. However, you will need to serve the files from a small server for the site to work. If you notice, when you run npm run build, the terminal will print a notice...
Tip:
Built files are meant to be served over an HTTP server.
Opening index.html over file:// won't work.
You can create a simple http server in your /dist directory with express and then host your site somewhere like Heroku.
Take a look at this article https://medium.com/#sagarjauhari/quick-n-clean-way-to-deploy-vue-webpack-apps-on-heroku-b522d3904bc8#.4nbg2ssy0
TLDR;
write a super simple express server
var express = require('express');
var path = require('path');
var serveStatic = require('serve-static');
app = express();
app.use(serveStatic(__dirname));
var port = process.env.PORT || 5000;
app.listen(port);
console.log('server started '+ port);
add a postinstall script in a package.json within /dist
{
"name": "myApp",
"version": "1.0.0",
"description": "awesome stuff",
"author": "me oh my",
"private": true,
"scripts": {
"postinstall": "npm install express"
}
}
push only your /dist folder to heroku after you've compiled your site.
proof: I've followed these steps to host my vue.js project
using vue files without NodeJS (nor webpack) is possible with vue3-sfc-loader.
vue3-sfc-loader
Vue3/Vue2 Single File Component loader. Load .vue files dynamically at runtime from your html/js. No node.js
environment, no (webpack) build step needed.
vue3-sfc-loader will parse your .vue file at runtime and create a ready-to-use Vue component.
disclamer: author here
Could you try something as simple as an S3 bucket setup for web serving? How big is your project? How much traffic do you think you'll get? If it's very small, you may be able to host on S3 and use webpack, etc.

Vue.js Webpack Template in a Docker Container: How do I add Webpack-Dev-Server --watch-poll flag?

I am running the webpack / webpack-dev-server portion of the base Vue.js Webpack template (https://github.com/vuejs-templates/webpack/) inside of a docker container I created. The container also contains the vue CLI in order to create new projects (you can get my container here if you want: https://hub.docker.com/r/ncevl/webpack-vue/).
Hot-reload does not work after moving from the webpack-simple template to this one.
Everything was working using the Webpack-Simple template which you can clone / see over here: https://github.com/vuejs-templates/webpack-simple
I was able to get the simple template running (with hot-reload working as intended) with the following webpack-development-server launch command:
webpack-dev-server --hot --inline --progress --host 0.0.0.0 --watch-poll
That said the full (not simple) version of the webpack template does not appear to use a webpack-dev-server launch command and instead appears to use additional middleware as referenced in build/dev-server.js (https://github.com/vuejs-templates/webpack/blob/master/template/build/dev-server.js) and the webpack dev config.
Since the --watch-poll was the key to getting the WDS hot-reload functionality to work within a docker container in the last project, my thinking is that I need to do something similar with the webpack-hot-middleware but I dont see anything in their docs (over here: https://github.com/glenjamin/webpack-hot-middleware) that talks about changing to a polling based approach.
I am not 100% sure the polling flag will do the trick since I can see the container recompile my source when I make a change. I can also see the change in my browser if I refresh it manually.
Whats stranger still is if I inspect my page in browser within chrome dev tools, and then head over to network / XHR I can see that the browser actually does receive information from the webpack-dev-server, but visually it does not update.
Give the above I assume websockets (or socket.io which I think is used) are working and communicating between the browser and the WDS so maybe this is a browser caching issue of some sort?
I checked in my console and found this so it is looking like a header issue:
For reference the text error from that image (to make it easier for anyone having the same issue to find this post) is:
EventSource cannot load http://__webpack_hmr/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://0.0.0.0:8080' is therefore not allowed access.
Again the Hot-Reload / Hot Module Reload was working with this identical container setup when using the webpack-simple Vue.js template.
I am wondering if anyone has run into anything similar or has any ideas on how to add the polling option . I guess my alternative would be roll back to a more basic webpack config and rebuild that portion of things to use the traditional webpack-dev-server / webpack config but give the above I am not sure that is going to fix it.
I am adding this as a separate answer since it more specifically answers the question in the title, while my other answer more specifically explains what solved my actual problem.
The vue.js webpack template project (which can either be init'd from the Vue CLI or pulled from its repo over here: https://github.com/vuejs-templates/webpack) separates its config files into several different directories.
I am posting this answer so that anyone who runs into the need to add polling to their project will be able to understand how / where to do that.
The base project structure for a Vue.js webpack template project looks like this:
The files that you care about if you are messing with trying to get hot module reload working are related to creating your server primarily with webpack-dev-middleware. The most important files related to that are highlighted here:
Basically if you want to add the polling code to the webpack-dev-middleware server you need to be in the /build/dev-server.js file on lines 20 to 24 that look like this:
var devMiddleware = require('webpack-dev-middleware')(compiler, {
publicPath: webpackConfig.output.publicPath,
quiet: true
})
To add polling you would add it just before or after quiet: true. As a side note, if you are having trouble with HMR I would change "quiet:true" to queit false to get a more verbose read out of whats going on from webpack-dev-middleware. I have included verbose and polling modifications to the above code here:
var devMiddleware = require('webpack-dev-middleware')(compiler, {
publicPath: webpackConfig.output.publicPath,
quiet: false, //Changed to for additional verbosity
watchOptions: { //Add Polling
aggregateTimeout: 300,
poll: 1000
}
})
My other answer is in regards to what ended up solving my problem, not necessarily how to actually add polling (which might be necessary for someone else but did not end up being needed to make my dockerized setup work).
It should also be noted that sometimes when HMR (webpack hot module reload) is not detecting changes it is due to the fact that webpack-hot-middleware or webpack-dev-middleware is running into an issue whereby some invisible characters are / were added to the name of the base project directory (probably by someone building the base Vue project) and therefore webpack on certain OSes is not able to see the changes.
If that happens to you and you are on OSx or running webpack inside of a docker container and you can't get HMR to detect changes, try to rename your vue-webpack project directory and it should work.
Ok. So I can't really take credit for this one since it was actually answered by Discuss user Cristian Pallarés over here: http://webpack.github.io/docs/webpack-dev-server.html#combining-with-an-existing-server
Christian says:
I was just trying the same. I just use "php artisan serve" on localhost:8000, and Webpack Dev Server on localhost:3000. You should make this:
set your webpack config "output.publicPath" as "http://localhost:3000/static/" instead of "/static/"
make your php application load this:
The key is the output.publicPath being absolute. Now, you should run "php artisan serve" and launch your webpack dev server too (in my case I use gulp).
Basically I took that and dug through the Vue.js Webpack Template files to locate the config file where webpack was looking for the public path. the public path setting ended up being in the index.js file located in the /config directory of the template.
I changed my code to look like this:
assetsSubDirectory: 'http://localhost:8080/static/', //!!Changed from /static/
assetsPublicPath: 'http://localhost:8080/', //!!Changed from /
As opposed to the previous setting which DID NOT WORK and looked like this:
assetsSubDirectory: '/static/',
assetsPublicPath: '/',
After that I was able to see my changes hot reload while running the vue.js Webpack template from within my docker container.

How do I use Webpack with ReactJS and NodeJS?

How do I use Webpack with ReactJS and NodeJS? My problem is both the server and client have source that needs to be transpiled through (babble et. al.) but the Webpack config file only has one output file.
What I need is my node app build and my client side app built and put in build/.
Webpack won't compile your server code. You'll need to configure babel to transpile your server code when the server starts. Why do you need both server and client code in a /build/ directory? It's better to keep them separate.

How to not bundle node_modules, but use them normally in node.js?

Architecture
I would like to share code between client and server side. I have defined aliases in the webpack config:
resolve: {
// Absolute paths: https://github.com/webpack/webpack/issues/109
alias: {
server : absPath('/src/server/'),
app : absPath('/src/app/'),
client : absPath('/src/client/'),
}
},
Problem
Now on the server side I need to include webpack in order to recognize the correct paths when I require a file. For example
require('app/somefile.js')
will fail in pure node.js because can't find the app folder.
What I need (read the What I need updated section)
I need to be able to use the webpack aliases. I was thinking about making a bundle of all the server part without any file from node_modules. In this way when the server starts it will use node_modules from the node_modules folder instead of a minified js file (Why? 1st: it doesn't work. 2nd: is bad, because node_modules are compiled based on platform. So I don't want my win files to go on a unix server).
Output:
Compiled server.js file without any node_modules included.
Let the server.js to use node_modules;
What I need updated
As I've noticed in https://github.com/webpack/webpack/issues/135 making a bundled server.js will mess up with all the io operation file paths.
A better idea would be to leave node.js server files as they are, but replace the require method provided with a custom webpack require which takes in account configurations such as aliases (others?)... Can be done how require.js has done to run on node.js server.
What I've tried
By adding this plugin in webpack
new webpack.optimize.CommonsChunkPlugin(/* chunkName= */"ignore", /* filename= */"server.bundle.js")
Entries:
entry: {
client: "./src/client/index.js",
server: "./src/server/index.js",
ignore: ['the_only_node_module'] // But I need to do that for every node_module
},
It will create a file server.js which only contains my server code. Then creates a server.bundle.js which is not used. But the problem is that webpack includes the webpackJsonp function in the server.bundle.js file. Therefore both the client and server will not work.
It should be a way to just disable node_modules on one entry.
What I've tried # 2
I've managed to exclude the path, but requires doesn't work because are already minified. So the source looks like require(3) instead of require('my-module'). Each require string has been converted to an integer so it doesn't work.
In order to work I also need to patch the require function that webpack exports to add the node.js native require function (this is easy manually, but should be done automatically).
What I've tried # 3
In the webpack configuration:
{target: "node"}
This only adds an exports variable (not sure about what else it does because I've diffed the output).
What I've tried # 4 (almost there)
Using
require.ensure('my_module')
and then replacing all occurrences of r(2).ensure with require. I don't know if the r(2) part is always the same and because of this might not be automated.
Solved
Thanks to ColCh for enlighten me on how to do here.
require = require('enhanced-require')(module, require('../../webpack.config'));
By changing the require method in node.js it will make node.js to pass all requires trough the webpack require function which allow us to use aliases and other gifts! Thanks ColCh!
Related
https://www.bountysource.com/issues/1660629-what-s-the-right-way-to-use-webpack-specific-functionality-in-node-js
https://github.com/webpack/webpack/issues/135
http://webpack.github.io/docs/configuration.html#target
https://github.com/webpack/webpack/issues/458
How to simultaneously create both 'web' and 'node' versions of a bundle with Webpack?
http://nerds.airbnb.com/isomorphic-javascript-future-web-apps/
Thanks
Thanks to ColCh for enlighten me on how to do here.
require = require('enhanced-require')(module, require('../../webpack.config'));
By changing the require method in node.js it will make node.js to pass all requires trough the webpack require function which allow us to use aliases and other gifts! Thanks ColCh!
My solution was:
{
// make sure that webpack will externalize
// modules using Node's module API (CommonJS 2)
output: { ...output, libraryTarget: 'commonjs2' },
// externalize all require() calls to non-relative modules.
// Unless you do something funky, every time you import a module
// from node_modules, it should match the regex below
externals: /^[a-z0-9-]/,
// Optional: use this if you want to be able to require() the
// server bundles from Node.js later
target: 'node'
}

Resources