簡體   English   中英

在Angular Universal中使用lodash-es的正確方法是什么?

[英]What is the right way to use lodash-es in Angular Universal?

當我將輸入從lodash替換為lodash-es時,Angular Universal服務器中斷。 但是,當我運行ng serve ,一切都很好。 我想使用lodash-es,以便可以在Angular SPA中挑選lodash函數並縮小包的大小。

我采取的步驟:npm卸載lodash ,npm安裝lodash-es ,並這樣替換導入:

來自: import { find as _find } from "lodash";

要: import { find as _find } from "lodash-es"

這是我得到的服務器錯誤:

/usr/src/app/node_modules/lodash-es/lodash.js:10
export { default as add } from './add.js';
^^^^^^
SyntaxError: Unexpected token export
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)
    at Module._compile (module.js:599:28)
    at Object.Module._extensions..js (module.js:646:10)
    at Module.load (module.js:554:32)
    at tryModuleLoad (module.js:497:12)
    at Function.Module._load (module.js:489:3)
    at Module.require (module.js:579:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/usr/src/app/dist/server.js:246:18)

server.ts

import "zone.js/dist/zone-node";
import "reflect-metadata";
import { renderModuleFactory } from "@angular/platform-server";
import { enableProdMode } from "@angular/core";

import * as express from "express";
import * as minifyHTML from "express-minify-html";
import { join } from "path";
import { readFileSync } from "fs";

// Faster server renders w/ Prod mode (dev mode never needed)
enableProdMode();

// Express server
const app = express();

const PORT = process.env.PORT || 4000;
const DIST_FOLDER = join(process.cwd(), "dist");

// Our index.html we'll use as our template
const template = readFileSync(
  join(DIST_FOLDER, "browser", "index.html")
).toString();

// * NOTE :: leave this as require() since this file is built Dynamically from webpack
const {
  AppServerModuleNgFactory,
  LAZY_MODULE_MAP
} = require("./dist/server/main.bundle");

// Express Engine
import { ngExpressEngine } from "@nguniversal/express-engine";
// Import module map for lazy loading
import { provideModuleMap } from "@nguniversal/module-map-ngfactory-loader";

app.use(
  minifyHTML({
    override: true,
    exception_url: false,
    htmlMinifier: {
      removeComments: true,
      collapseWhitespace: true,
      collapseBooleanAttributes: true,
      removeAttributeQuotes: true,
      removeEmptyAttributes: true,
      minifyJS: true,
      minifyCSS: true
    }
  })
);

// Our Universal express-engine (found @ https://github.com/angular/universal/tree/master/modules/express-engine)
app.engine(
  "html",
  ngExpressEngine({
    bootstrap: AppServerModuleNgFactory
  })
);

app.set("view engine", "html");
app.set("views", join(DIST_FOLDER, "browser"));

/* - Example Express Rest API endpoints -
  app.get('/api/**', (req, res) => { });
*/

// Server static files from /browser
app.get(
  "*.*",
  express.static(join(DIST_FOLDER, "browser"), {
    maxAge: "1y"
  })
);

// ALl regular routes use the Universal engine
app.get("*", (req, res) => {
  res.render("index", { req });
});

// Start up the Node server
app.listen(PORT, () => {
  console.log(`Node Express server listening on http://localhost:${PORT}`);
});

這是webpack.server.config.js (可能相關嗎?):

const path = require("path");
const webpack = require("webpack");
const nodeExternals = require("webpack-node-externals");

module.exports = {
  entry: { server: "./server.ts" },
  resolve: { extensions: [".ts", ".js"] },
  target: "node",
  externals: [nodeExternals()],
  output: {
    path: path.join(__dirname, "dist"),
    filename: "[name].js"
  },
  module: {
    rules: [{ test: /\.ts$/, loader: "ts-loader" }]
  },
  plugins: [
    new webpack.DefinePlugin({
      window: undefined,
      document: undefined
    }),
    new webpack.ContextReplacementPlugin(
      /(.+)?angular(\\|\/)core(.+)?/,
      path.join(__dirname, "src"), // location of your src
      {} // a map of your routes
    ),
    new webpack.ContextReplacementPlugin(
      /(.+)?express(\\|\/)(.+)?/,
      path.join(__dirname, "src")
    )
  ]
};

解決方案是將lodash-es列入白名單,就像David在對原始問題的評論中所建議的那樣。 具體來說,現在webpack.server.config.js看起來像這樣:

...
  externals: [
    nodeExternals({
      whitelist: [/^lodash-es/]
    })
  ],
...

Angular 2+是打字稿..因此,您需要使用以下命令從npm安裝@ types / lodash

npm install --save @types/lodash

那么您需要將其導入組件,例如:

import * as lodash from 'lodash';

你可以像這樣使用lodash

lodash.find()  etc...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM