Я использую PKG для объединения проекта и создания исполняемого файла, вот в чем проблема, есть ли какое-либо решение или другой способ сделать это?
> Error! Unexpected token (221:12)
/home/arnab/vpn-web-node/server/server.js
Я поставил сервер. js как в положение bin в пакете. json мой сервер. js
<code>import Express from "express";
import compression from "compression";
import mongoose from "mongoose";
import bodyParser from "body-parser";
import path from "path";
import IntlWrapper from "../client/modules/Intl/IntlWrapper";
import session from "express-session";
import { Auth } from "./middlewares/Auth";
// Initialize the Express App
const app = new Express();
// Set Development modes checks
const isDevMode = process.env.NODE_ENV === "development" || false;
const isProdMode = process.env.NODE_ENV === "production" || false;
// Run Webpack dev server in development mode
if (isDevMode) {
// Webpack Requirements
// eslint-disable-next-line global-require
const webpack = require("webpack");
// eslint-disable-next-line global-require
const config = require("../webpack.config.dev");
// eslint-disable-next-line global-require
const webpackDevMiddleware = require("webpack-dev-middleware");
// eslint-disable-next-line global-require
const webpackHotMiddleware = require("webpack-hot-middleware");
const compiler = webpack(config);
app.use(
webpackDevMiddleware(compiler, {
noInfo: true,
publicPath: config.output.publicPath,
watchOptions: {
poll: 1000
}
})
);
app.use(webpackHotMiddleware(compiler));
}
// React And Redux Setup
import { configureStore } from "../client/store";
import { Provider } from "react-redux";
import React from "react";
import { renderToString } from "react-dom/server";
import { match, RouterContext } from "react-router";
import Helmet from "react-helmet";
import { enabledLanguages, localizationData } from "../Intl/setup";
// Import required modules
import routes from "../client/routes";
import { fetchComponentData } from "./util/fetchData";
import api from "./routes/Api";
import login from "./routes/login";
import dummyData from "./dummyData";
import serverConfig from "./config";
import { getallcount } from "./controllers/user.controller";
// Set native promises as mongoose promise
mongoose.Promise = global.Promise;
// MongoDB Connection
if (process.env.NODE_ENV !== "test") {
mongoose.connect(
serverConfig.mongoURL,
error => {
if (error) {
console.error("Please make sure Mongodb is installed and running!"); // eslint-disable-line no-console
throw error;
}
// feed some dummy data in DB.
dummyData();
}
);
}
// Apply body Parser and server public assets and routes
app.use(compression());
app.use(
session({
secret: "vpn by darkbears", //1 Hour
cookie: { maxAge: 24 * 360000 }
})
);
app.use(bodyParser.json({ limit: "20mb" }));
app.use(bodyParser.urlencoded({ limit: "20mb", extended: false }));
app.use(Express.static(path.resolve(__dirname, "../dist/client")));
app.get("*.js", function(req, res, next) {
req.url = req.url + ".gz";
res.set("Content-Encoding", "gzip");
next();
});
app.use("/admin/user", Auth, api);
app.use("/admin/server", Auth, api);
app.use("/admin/app", Auth, api);
app.use("/admin/reseller", Auth, api);
app.use("/admin/dashboard", Auth, api);
app.use("/admin/reports", Auth, api);
app.use("/admin", Auth, api);
app.use("/account", login);
// mongoose.set("debug", true);
// mongoose.set('debug', function (coll, method, query, doc ) {
// //do your thing
// console.log("queryLog: ",query);
// });
// Render Initial HTML
const renderFullPage = (html, initialState) => {
const head = Helmet.rewind();
// Import Manifests
const assetsManifest =
process.env.webpackAssets && JSON.parse(process.env.webpackAssets);
const chunkManifest =
process.env.webpackChunkAssets &&
JSON.parse(process.env.webpackChunkAssets);
return `
<!doctype html>
<html>
<head>
${head.base.toString()}
${head.title.toString()}
${head.meta.toString()}
${head.link.toString()}
${head.script.toString()}
${
isProdMode
? `<link rel='stylesheet' href='${assetsManifest["/app.css"]}' />`
: ""
}
<link href='https://fonts.googleapis.com/css?family=Lato:400,300,700' rel='stylesheet' type='text/css'/>
</head>
<body>
<div id="root">${
process.env.NODE_ENV === "production" ? html : `<div>${html}</div>`
}</div>
<script>
window.__INITIAL_STATE__ = ${JSON.stringify(initialState)};
${
isProdMode
? `//<![CDATA[
window.webpackManifest = ${JSON.stringify(chunkManifest)};
//]]>`
: ""
}
</script>
<script src='${
isProdMode ? assetsManifest["/vendor.js"] : "/vendor.js"
}'></script>
<script src='${
isProdMode ? assetsManifest["/app.js"] : "/app.js"
}'></script>
</body>
</html>
`;
};
const renderError = err => {
const softTab = "    ";
const errTrace = isProdMode
? `:<br><br><pre style="color:red">${softTab}${err.stack.replace(
/\n/g,
`<br>${softTab}`
)}
`:" "; return renderFullPage (`Ошибка сервера $ {errTrace}`, {}); }; // Рендеринг на стороне сервера на основе маршрутов, соответствующих React-маршрутизатору. app.use ((req, res, next) => {match ({маршруты, местоположение: req.url}, (err, redirectLocation, renderProps) => {if (err) {вернуть res.status (500) .end (renderError (err));} if (redirectLocation) {return res.redirect (302, redirectLocation.pathname + redirectLocation.search);} if (! renderProps) {return next ();} const initLocale = req.session.lang || "en"; getallcount (). then ((eer, count) => {var countts = {}; var userlogin = {}; if (req.session.user) {userlogin = {userLogin: {isloggedin: true , isAuth: true, загрузка: false, ошибка: false, пользователь: req.session.user}, count: count, intl: {locale: initLocale, enabledLanguages, ... (localizationData [initLocale] || {}),} };} const store = configureStore (userlogin); вернуть fetchComponentData (store, renderProps.components, renderProps.params) .then (() => {const initialView = renderToString ( ); const finalState = store.getState (); res .set ("Content-Type", "text / html") .status (200) .end (renderFullPage (initialView, finalState)); }) .catch (ошибка => следующая (ошибка)); }); }); }); app.listen (serverConfig.port, error => {if (! error) {console.log (`MERN работает на порту: $ {serverConfig.port}! Создайте что-нибудь удивительное!`); // eslint-disable-line }}); экспорт приложения по умолчанию;
index. js (узел запускает файл внутри пакета. json npm start)
/**
* Entry Script
*/
if (process.env.NODE_ENV === 'production') {
process.env.webpackAssets = JSON.stringify(require('./dist/client/manifest.json'));
process.env.webpackChunkAssets = JSON.stringify(require('./dist/client/chunk-manifest.json'));
// In production, serve the webpacked server file.
require('./dist/server.bundle.js');
} else {
// Babel polyfill to convert ES6 code in runtime
require('babel-register')({
"plugins": [
[
"babel-plugin-webpack-loaders",
{
"config": "./webpack.config.babel.js",
"verbose": false
}
]
]
});
require('babel-polyfill');
require('./server/server');
}
package. json
"name": "@hashnode/mern-starter",
"version": "2.4.0",
"description": "Boilerplate project for building Isomorphic apps using React and Redux",
"scripts": {
"test": "cross-env NODE_ENV=test PORT=8080 MONGO_URL=mongodb://localhost:27017/mern-test node_modules/.bin/nyc node node_modules/ava/cli.js",
"watch:test": "npm run test -- --watch",
"cover": "nyc npm run test",
"check-coverage": "nyc check-coverage --statements 100 --branches 100 --functions 100 --lines 100",
"start": "cross-env BABEL_DISABLE_CACHE=1 NODE_ENV=development node index.js",
"start:prod": "cross-env NODE_ENV=production node index.js",
"bs": "npm run clean && npm run build && npm run build:server && npm run start:prod",
"build": "cross-env NODE_ENV=production webpack --config webpack.config.prod.js",
"build:server": "cross-env NODE_ENV=production webpack --config webpack.config.server.js",
"clean": "rimraf dist",
"slate": "rimraf node_modules && npm install",
"lint": "eslint client server"
},
"pre-commit": [
"lint",
"test"
],
"repository": {
"type": "git",
"url": "git+https://github.com/Hashnode/mern-starter.git"
},
"bugs": {
"url": "https://github.com/Hashnode/mern-starter/issues"
},
"homepage": "https://github.com/Hashnode/mern-starter#readme",
"author": "Prashant Abhishek <prashant.abhishek7g@gmail.com>, Mayank Chandola <imayankchd@gmail.com>, Sandeep Panda <sandeep@hashnode.com>, Syed Fazle Rahman <fazle@hashnode.com>, Alkshendra Maurya <alkshendra@hashnode.com>",
"license": "MIT",
"dependencies": {
"@material-ui/core": "^3.6.2",
"@material-ui/icons": "^3.0.1",
"aes-js": "^3.1.2",
"axios-fileupload": "0.0.1",
"babel-core": "^6.26.0",
"bcrypt": "^3.0.2",
"body-parser": "^1.15.1",
"bootstrap": "3.3.7",
"chartist": "^0.11.0",
"compression": "^1.6.2",
"cross-env": "^1.0.8",
"cuid": "^1.3.8",
"express": "^4.13.4",
"express-session": "^1.15.6",
"font-awesome": "^4.7.0",
"fs": "0.0.1-security",
"intl": "^1.2.4",
"intl-locales-supported": "^1.0.0",
"is-ip": "^3.1.0",
"isomorphic-fetch": "^2.2.1",
"limax": "^1.3.0",
"material-ui": "^0.20.2",
"migrate": "^1.6.2",
"mongoose": "^4.4.20",
"mui-datatables": "^2.0.0-beta-45",
"namor": "^1.1.1",
"prop-types": "^15.6.2",
"react": "^16.4.1",
"react-blob": "^1.0.1",
"react-bootstrap": "^0.32.4",
"react-chartist": "^0.13.1",
"react-dom": "^16.4.1",
"react-dropzone": "^10.2.1",
"react-helmet": "^5.2.0",
"react-intl": "^2.1.2",
"react-intl-tel-input": "^5.0.7",
"react-notification-system": "^0.2.17",
"react-redux": "^4.4.5",
"react-router": "^3.2.1",
"react-router-dom": "^4.3.1",
"react-select": "^3.0.8",
"react-table": "^6.8.6",
"reactjs-file-uploader": "^1.0.8",
"redux": "^3.5.2",
"redux-form": "^8.0.4",
"redux-thunk": "^2.1.0",
"sanitize-html": "^1.11.4",
"sass-loader": "^7.1.0",
"shelljs": "^0.8.3"
},
"devDependencies": {
"ava": "^0.15.2",
"babel-eslint": "^6.0.4",
"babel-loader": "^7.1.2",
"babel-plugin-webpack-loaders": "^0.9.0",
"babel-polyfill": "^6.26.0",
"babel-preset-es2015": "^6.9.0",
"babel-preset-es2015-native-modules": "^6.6.0",
"babel-preset-react": "^6.5.0",
"babel-preset-react-optimize": "^1.0.1",
"babel-preset-stage-0": "^6.5.0",
"babel-register": "^6.26.0",
"chai": "^3.5.0",
"chunk-manifest-webpack-plugin": "^1.1.2",
"coveralls": "^3.0.2",
"css-loader": "^0.28.7",
"css-modules-require-hook": "^4.2.2",
"cssnano": "^3.7.0",
"enzyme": "^3.3.0",
"enzyme-adapter-react-16": "^1.1.1",
"eslint": "^2.11.1",
"eslint-config-airbnb": "^9.0.1",
"eslint-plugin-ava": "^2.4.0",
"eslint-plugin-import": "^1.8.1",
"eslint-plugin-jsx-a11y": "^1.3.0",
"eslint-plugin-react": "^5.1.1",
"eventsource-polyfill": "^0.9.6",
"extract-text-webpack-plugin": "^3.0.2",
"file-loader": "^0.8.5",
"jsdom": "^9.2.1",
"mock-css-modules": "^1.0.0",
"mockgoose": "^7.3.5",
"nock": "^10.0.4",
"nodemon": "^1.19.4",
"null-loader": "^0.1.1",
"nyc": "^13.1.0",
"postcss-cssnext": "^2.6.0",
"postcss-focus": "^1.0.0",
"postcss-loader": "^2.0.9",
"postcss-reporter": "^1.3.3",
"pre-commit": "^1.1.3",
"raf": "^3.4.0",
"react-addons-test-utils": "^15.1.0",
"react-hot-loader": "^3.0.0-beta.2",
"redux-ava": "^2.0.0",
"redux-devtools": "^3.3.1",
"redux-devtools-dock-monitor": "^1.1.1",
"redux-devtools-log-monitor": "^1.0.11",
"rimraf": "^2.5.2",
"sinon": "^1.17.4",
"style-loader": "^0.19.1",
"supertest": "^3.3.0",
"url-loader": "^1.1.2",
"webpack": "^3.10.0",
"webpack-dev-middleware": "^1.12.2",
"webpack-dev-server": "^3.1.10",
"webpack-hot-middleware": "^2.21.0",
"webpack-manifest-plugin": "^1.3.2",
"webpack2-externals-plugin": "^1.0.0"
},
"engines": {
"node": ">=6"
},
"ava": {
"files": [
"client/**/*.spec.js",
"server/**/*.spec.js"
],
"source": [
"client/**/*.js",
"server/**/*.js"
],
"failFast": true,
"babel": "inherit",
"require": [
"./server/util/setup-test-env.js"
]
},
"nyc": {
"include": [
"client/**/*.js",
"server/**/*.js"
],
"exclude": [
"**/*.spec.js",
"client/reducers.js",
"client/store.js",
"client/routes.js",
"server/util/setup-test-env.js",
"server/util/test-helpers.js",
"server/config.js",
"server/dummyData.js"
],
"reporter": [
"lcov",
"text",
"html"
]
}
}
Я чувствовал, что это не правильный способ сделать это для приложения mern-cli hashnode. Я следил за этим https://www.npmjs.com/package/pkg и https://github.com/zeit/pkg