【问题标题】:TypeScript + moment.js: error TS2307: Cannot find module 'moment'TypeScript + moment.js:错误 TS2307:找不到模块'moment'
【发布时间】:2017-12-10 03:07:03
【问题描述】:

我正在开发一个网络应用程序,使用 angular 1.5、typescript 2.4.0、moment: 2.18.1 和 gulp 进行项目组装。

这是我的tsconfig.json

{
  "files": [
    "src/app/main.ts",
    "types/**/*.ts"
  ],
  "compilerOptions": {
    "noImplicitAny": false,
    "target": "es2015",
    "allowSyntheticDefaultImports": true
  }
}

在我的date-range-picker.component.ts 里面。我正在导入时刻库,正如main documentation 中所建议的那样:

import * as moment from 'moment'; 

这对于依赖 tsify 插件的主要 gulp 项目组装任务效果很好。:

var browserifyIt = browserify({
    basedir: '.',
    debug: true,
    entries: paths.browserifyEntries,
    cache: {},
    packageCache: {}
}).plugin(tsify);

gulp.task('bundle', ['views'], function () {
    return browserifyIt
        .transform('babelify', {
            presets: ['es2015'],
            extensions: ['.ts']
        })
        .bundle()
        .on('error', interceptErrors)
        .pipe(source(fileNames.buildJs))
        .pipe(ngAnnotate())
        .pipe(buffer())
        .pipe(sourcemaps.init({loadMaps: true}))
        .pipe(sourcemaps.write(paths.sourcemapPath))
        .pipe(gulp.dest(paths.build));
});

但是为了编译测试,我决定使用使用 tsProject() 的任务:

const testSrcPaths = {
    ....,
    componentTests: 'src/app/components/**/*.test.ts',
    ....
};
gulp.task('component-tests:compile', function () {
       return gulp.src(testSrcPaths.componentTests).pipe(tsProject())
        .on('error', interceptErrors)
        .js.pipe(gulp.dest(`${paths.testsDist}/components`));
});

这会导致以下错误:

date-range-picker/date-range-picker.component.ts(2,25):错误 TS2307: 找不到模块“时刻”。

有什么办法可以解决?

【问题讨论】:

  • 你可以试试 var tsProject = ts.createProject('tsconfig.json',{ }); ,也许这有帮助
  • 结果是一样的

标签: javascript angularjs typescript gulp momentjs


【解决方案1】:

最后,将moduleResolution: "node" 添加到compilerOptions 解决了我的问题。所以最后采用了以下tsconfig.json配置:

{
  "files": [
    "src/app/main.ts"
  ],
  "compilerOptions": {
    "noImplicitAny": false,
    "target": "es2015",
    "moduleResolution": "node"
  }
}

这里是link,可以用来了解有关打字稿模块解析方法的更多信息。

【讨论】:

  • 感谢您的链接。将 moduleResolution 设置为 node 可以大量破坏旧的/现有的代码。使用 tsconfig 中的 pathsbaseUrl 属性来恢复顺序:-)
猜你喜欢
  • 2019-02-11
  • 1970-01-01
  • 2017-03-18
  • 2017-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-29
  • 2018-08-29
相关资源
最近更新 更多