Ricerca nel sito web

javascript - TypeScript + moment.js: errore TS2307: Impossibile trovare il modulo 'moment'


Sto sviluppando un'app web, usando Angular 1.5, TypeScript 2.4.0, Moment 2.18.1 e Gulp per l'assemblaggio del progetto.

Ecco il mio tsconfig.json:

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

All'interno del mio date-range-picker.component.ts. Sto importando la libreria moment, come proposto nella documentazione principale:

import * as moment from 'moment'; 

Che funziona bene per il compito principale di assemblaggio del progetto gulp che si basa sul plugin tsify.

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));
});

Ma per la compilazione dei test ho deciso di usare un task che utilizza 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`));
});

Il che porta al seguente errore:

date-range-picker/date-range-picker.component.ts(2,25): errore TS2307: Impossibile trovare il modulo 'moment'.

Cosa si può fare per risolverlo?

Risposta n. 1

Infine, aggiungere moduleResolution: "node" a compilerOptions ha risolto il mio problema. Quindi alla fine viene utilizzata la seguente configurazione tsconfig.json:

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

Ecco il link che si può usare per saperne di più sugli approcci di risoluzione dei moduli in TypeScript.

Articoli correlati