Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript : require statement not part of an import statement

People also ask

Can we use require in TypeScript?

TypeScript offers support for creating and using modules with a unified syntax that is similar to the ES Module syntax, while allowing the developer to output code that targets different module loaders, like Node. js (CommonJS), require.

What is require () in JavaScript?

1) require() In NodeJS, require() is a built-in function to include external modules that exist in separate files. require() statement basically reads a JavaScript file, executes it, and then proceeds to return the export object.

Does TypeScript use import?

Importing TypesWith TypeScript 3.8, you can import a type using the import statement, or using import type .


TypeScript modules are an implementation of ES6 modules. ES6 modules are static. Your issue comes from the dynamic path: path.join(process.cwd() + "/data"). The compiler can't determine which module it is at compile time, and the linter doesn't like the causes that lead to any.

You should use a static path to the module. At compile time, TypeScript resolves it. And it affects the right exported type (IUser[]) to users.

import users = require("./yourModuleThatExportsUsers");

Notice: If your module data contains just data, you could consider to change it to a JSON file, which could be loaded (Node.js) or bundled (Webpack).

UPDATE (from May 2019) — It is also possible to use dynamic import, with which TypeScript accepts static and dynamic paths:

const users = await import("./yourModuleThatExportsUsers");

See also: TypeScript 2.4 Release Notes


may be you need dynamic module loading, and the code like this:

import {IUser} from './lib/user';
const users:IUser[] = require(path.join(process.cwd() + "/data"));

if your can run the code correctly but eslint report an error, you can add /* eslint-disable */above you error code like this


/* eslint-disable */
const path =  require("path");
module.exports = {
    lintOnSave: false,
    chainWebpack: config => {

        const dir = path.resolve(__dirname, "src/assets/icons");

        config.module
            .rule("svg-sprite")
            .test(/\.svg$/)
            .include.add(dir).end() // 包含 icons 目录
            .use("svg-sprite-loader").loader("svg-sprite-loader").options({extract: false}).end();
        /* eslint-disable */
        config.plugin("svg-sprite").use(require("svg-sprite-loader/plugin"), [{plainSprite: true}] || []);
        config.module.rule("svg").exclude.add(dir); // 其他 svg loader 排除 icons 目录
    }
};