【问题标题】:A ts script in my Angular app can't find the modules in node_modules我的 Angular 应用程序中的 ts 脚本在 node_modules 中找不到模块
【发布时间】:2019-08-29 16:09:49
【问题描述】:

我有一个 Angular 应用程序。 我想在 package.json 中添加一个脚本。

脚本是用Typescript编写的,他的路径是src/scripts/generate-blog-metadata.ts。

const { promisify } = require('util');
const { resolve, join } = require('path');
const {fs} = require('fs');
const readdir = promisify(fs.readdir);
const stat = promisify(fs.stat);

我的 package.json :

  "scripts": {
    "generate-blog-metadata" : "node src/scripts/generate-blog-metadata.ts"
  },

当我运行脚本时:

npm run generate-blog-metadata

我得到一个错误:

/Users/pom/workspace/signalement-app/src/scripts/generate-blog-metadata.ts:6
const readdir = promisify(fs.readdir);
                             ^

TypeError: Cannot read property 'readdir' of undefined
    at Object.<anonymous> (/Users/john/workspace/signalement-app/src/scripts/generate-blog-metadata.js:6:30)

我的理解是我运行脚本的方式使他无法找到 node_modules。

可能是webpack配置问题,所以这是配置文件:

const path = require('path');
const webpack = require('webpack');

module.exports = {
  entry: {
    server: './server.ts',
  },
  target: 'node',
  resolve: {extensions: ['.ts', '.js']},
  externals: [/(node_modules|main\..*\.js)/,],
  output: {
    libraryTarget: 'commonjs2',
    path: path.join(__dirname, 'dist'),
    filename: '[name].js'
  },
  module: {
    rules: [
      {test: /\.ts$/, loader: 'ts-loader'}
    ]
  },
  optimization: {
    minimize: false
  },
  plugins: [
    new webpack.ContextReplacementPlugin(
      // fixes WARNING Critical dependency: the request of a dependency is an expression
      /(.+)?angular(\\|\/)core(.+)?/,
      path.join(__dirname, 'src'), // location of your src
      {} // a map of your routes
    ),
    new webpack.ContextReplacementPlugin(
      // fixes WARNING Critical dependency: the request of a dependency is an expression
      /(.+)?express(\\|\/)(.+)?/,
      path.join(__dirname, 'src'),
      {}
    )
  ]
}

【问题讨论】:

    标签: angular typescript webpack


    【解决方案1】:

    我认为您应该将扩展名 generate-blog-metadata.js 更改为 generate-blog-metadata.ts

    【讨论】:

    • 谢谢,但 .ts 和 .js 存在错误。我更正了我的问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-29
    • 2017-07-02
    • 2020-07-22
    • 2017-11-10
    • 1970-01-01
    • 2020-09-05
    • 1970-01-01
    相关资源
    最近更新 更多