【问题标题】:how to declare a node import in typescript compiler to ignore it in compiled file?如何在打字稿编译器中声明节点导入以在编译文件中忽略它?
【发布时间】:2021-11-30 11:46:39
【问题描述】:

您好,在尝试理解typescripttypescript compiler 时,我尝试了一个小网络项目。

工作流程很简单。 typescript compiler 监视 src/js 文件夹并将每个 *.tsfile 编译到我的 dev_static/js 文件夹中作为 *.jsfile 并复制文件夹结构。

如有必要,我的django dev server 会从那里获取*.js文件。例如page_1.html 需要脚本 <script type="module" src="{% static 'js/pages/page_1.js' %}"> </script>

src/
   js/
      pages/page_1.ts
      pages/page_2.ts
      navbar/navbar.ts
      modules/some_modul.ts


dev_static/
          js/
            pages/page_1.js
            pages/page_2.js
            navbar/navbar.js
            modules/some_modul.js

.tsconfig

{
    "compilerOptions": {
        "outDir": "../dev_static/js",
        "removeComments": true,
        "target": "ES6",       
         "lib": [
            "es6",
            "dom",
            "es2015.promise"
        ],
        "allowJs": true,
        "checkJs": true,
        "moduleResolution": "node",
        "baseUrl": ".",
        "paths": {
            "~*": ["./*"],
            "@node/*": ["./node_modules/*"]
        },
    },
    // Input Dir
    "include": ["src/**/*"],
    "exclude": ["node_modules", "**/*.spec.ts"]
}

问题

将模块导入为 ES6 可以正常工作。但是我正在努力在我的打字稿项目中声明像 Axios 这样的第 3 方库。例如使用 axios 的类型和智能感知,我将 Axios 作为节点模块导入,如下所示:

axios_fetch.ts

import axios from '@node/axios'; 
import { graphUrl } from '../env/env.js'; 

编译器输出:

axios_fetch.js

import axios from '@node/axios';
import { graphUrl } from '../env/env.js';

当然浏览器不知道如何解决这个问题:import axios from '@node/axios';

2127.0.0.1/:1 Uncaught TypeError: Failed to resolve module specifier "@node/axios". Relative references must start with either "/", "./", or "../".

此外,我在我的开发服务器中加载了axios min.version(或其他第 3 方库)全局。它嵌入在一个基础模板中,其他所有页面都基于该模板,并且默认情况下每个页面都包含<script type="module" src="{% static 'js/3rdParty/axios/axios.min.js' %}"> </script>

dev_static/
          js/
            pages/page_1.js
            <...>
            3rdParty/axios/axios.min.js

问题

如何告诉编译器不要编译我的打字稿文件中的import axios from '@node/axios'; 行?因为 Axios 库将在我的所有页面(模板)中作为缩小版本提供或加载全局。我只需要这一行,这样打字稿就不会抱怨并且有可用的类型。

我需要的是 typescript compiler 在编译时不处理 axios 的“导入”行。或者换句话说,我只需要在 dev-compile-time 中导入该节点以进行类型检查、接口等,而不是在完成的 javascript 文件或运行时中。

axios_fetch.ts

    import axios from '@node/axios';// do not compile this. "axios" will be global available
    import { graphUrl } from '../env/env.js';

如果我在axios_fetch.js 中手动删除import axios from '@node/axios';,它会起作用。

【问题讨论】:

    标签: javascript typescript ecmascript-6 axios typescript-compiler-api


    【解决方案1】:

    好吧,经过几天的研究,我找到了这个解决方案,它对我有用。 Typescript 不再抱怨或将类型 import 行导出到我的编译文件中,同时仍然可以访问我的 *.ts 文件中的类型和智能感知。


    首先我在tsconfig.json 中进行了一点更改,声明"importsNotUsedAsValues":"remove" 非常重要。

    tsconfig.json

    {
        "compilerOptions": {
            // Output Dir
            "outDir": "../dev_static/js",
            "removeComments": true,
            // Compile to. What JS Versions.
            "target": "ES6",       
             "lib": [
                "es6",
                "dom",
                "es2015.promise"
            ],
            // allows also normal JS files
            "allowJs": true,
            // Normal JS file also be checked
            "checkJs": true,
            // important for import modules etc.
            "module": "es2015",
            "moduleResolution": "node",
            "importsNotUsedAsValues":"remove",
            "baseUrl": ".",
            "paths": {
                "~*": ["./*"],
                "@node/*": ["./node_modules/*"]
            },   
             "types": ["axios"]
    
        },
        // Input Dir
        "include": ["src/**/*"],
        "exclude": ["node_modules", "**/*.spec.ts"]
    }
    

    然后我从 axios 节点版本中仅导入所需的类型并将其声明为全局。但是你也可以简单地从 axios git repo 下载 index.d.ts 类型的文件并放入你的文件夹中。从tsconfig 中删除"types": ["axios"] 并使用import {AxiosStatic} from './axios'; 导入

    换句话说,第一行导入types,我只需要在这个*.ts文件中而不是稍后在我编译的*.js文件中。第二个导入行将一个名为 graphUrlvariable 作为 ES6 模块导入,另一方面,我稍后将在编译文件中需要该引用。

    axios_fetch.ts

    import { AxiosStatic } from 'axios'; // import the specific types from nodes axios 
    import { graphUrl } from '../env/env.js'; // that some es6 module vars i need also later
    
    declare global {
        const axios: AxiosStatic ;
    } 
    
    // AXIOS Client
    export const clientA = axios.create({
        baseURL: graphUrl,
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': csrftoken,
        } });
    

    所以 declare global typescript 似乎不必担心不导出 const axios: AxiosStatic 或满足所有类型需求 (importsNotUsedAsValues),因为它现在知道将在全球范围内进行存款。

    axios_fetch.js

    import { graphUrl } from '../env/env.js';
    const csrftoken = getCookie(cookieName);
    export const clientA = axios.create({
        baseURL: graphUrl,
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': csrftoken,
        }
    });
    

    现在在没有import { AxiosStatic } from 'axios'; 类型的行的情况下编译它。

    【讨论】:

      猜你喜欢
      • 2017-02-13
      • 2022-11-15
      • 1970-01-01
      • 2021-11-09
      • 1970-01-01
      • 2012-12-12
      • 2019-02-04
      • 2018-01-18
      • 2014-10-23
      相关资源
      最近更新 更多