簡體   English   中英

如何在用 TypeScript 編寫的 VS Code 擴展中導入 ES6 JavaScript 模塊?

[英]How do I import an ES6 JavaScript module in my VS Code extension written in TypeScript?

我正在 TypeScript 中開發一個 VS 代碼擴展,我正在嘗試從 npm 導入一個 JavaScript 庫,該庫在其 package.json 中與"type": "module",打包在一起。

如果我只是簡單地import * as mylib from mylib我會收到此錯誤消息:

激活擴展 'undefined_publisher.curlconverter' 失敗:必須使用導入加載 ES 模塊:/Users/space/code/curlconverter-extension/curlconverter/node_modules/curlconverter/index.js require() 不支持 ES 模塊。 /Users/space/code/curlconverter-extension/curlconverter/node_modules/curlconverter/index.js 的 require() 來自 /Users/space/code/curlconverter-extension/curlconverter/out/extension.js 是一個 ES 模塊文件,因為它是一個 .js 文件,其最近的父級 package.json 包含 "type": "module" ,它將 package scope 中的所有 .js 文件定義為 ES 模塊。 而是將 index.js 重命名為以 .cjs 結尾,將需要的代碼更改為使用 import(),或從 /Users/space/code/curlconverter-extension/curlconverter/node_modules/curlconverter/package 中刪除“type”:“module”。 json。 .

這告訴我從out/extension.js中的 TS 生成的 JS 正在使用require()語句來嘗試加載該 ES6 模塊,但顯然失敗了。

我試圖通過將此行添加到我的tsconfig.json來生成使用import的代碼

        "module": "ES2020",

但是當我運行我的擴展命令時,我收到了這個錯誤消息(即使我注釋掉了那個庫的導入語句,所以我的擴展只是注冊了一個什么都不做的命令):

激活擴展“undefined_publisher.curlconverter”失敗:無法在模塊外使用導入語句。

我是否需要添加一個package.json"type": "module",out/或其他東西?

是的,這是一種痛苦。 具體來說,你可以在 vscode 中使用 es6 模塊開發和調試擴展,但不能部署它們。 當您執行 vsix package 時,您會收到錯誤消息(最近)。

而且 ist 看起來不會很快改變: https://github.com/electron/electron/issues/21457

但是,我們不想再在 commonjs 模塊中編寫代碼了。 好消息 - 正如我們發現的那樣,有一個既令人愉快又可自動化的解決方法:

  1. es6 中的代碼僅使用根插件文件中的動態導入。 對於動態導入在 es6 和 commonjs 中都有效。 ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#dynamic_imports )
  2. 如您所願(使用 F5)針對 es6 模塊進行調試。
  3. 通過將 es6 模塊快速轉換為 cjs 到 es6 進行部署,例如使用類型腳本編譯器,如下所示: npx tsc -p tsconfig.json

使用 tsconfing.json 之類的

{
    "exclude": [ "node_modules", "cjs" ],
  "compilerOptions": {
    /* Visit https://aka.ms/tsconfisg.json to read more about this file */

    /* Basic Options */
    // "incremental": true,                         /* Enable incremental compilation */
    "target": "esnext",                                /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'. */
    "module": "commonjs",                           /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
    /// "lib": [ "ESNext"],                                   /* Specify library files to be included in the compilation. */
    "allowJs": true,                             /* Allow javascript files to be compiled. */
    "checkJs": false,                             /* Report errors in .js files. */
    // "jsx": "preserve",                           /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */
    // "declaration": true,                         /* Generates corresponding '.d.ts' file. */
    // "declarationMap": true,                      /* Generates a sourcemap for each corresponding '.d.ts' file. */
    // "sourceMap": true,                           /* Generates corresponding '.map' file. */
    // "outFile": "./",                             /* Concatenate and emit output to single file. */
    "outDir": "./cjs",                              /* Redirect output structure to the directory. */
    // "rootDir": "./",                             /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    // "composite": true,                           /* Enable project compilation */
    // "tsBuildInfoFile": "./",                     /* Specify file to store incremental compilation information */
    // "removeComments": true,                      /* Do not emit comments to output. */
    // "noEmit": true,                              /* Do not emit outputs. */
    // "importHelpers": true,                       /* Import emit helpers from 'tslib'. */
    "downlevelIteration": true,                  /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
    // "isolatedModules": true,                     /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

    /* Strict Type-Checking Options */
    // "strict": true,                                 /* Enable all strict type-checking options. */
    // "noImplicitAny": true,                       /* Raise error on expressions and declarations with an implied 'any' type. */
    // "strictNullChecks": true,                    /* Enable strict null checks. */
    // "strictFunctionTypes": true,                 /* Enable strict checking of function types. */
    // "strictBindCallApply": true,                 /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
    // "strictPropertyInitialization": true,        /* Enable strict checking of property initialization in classes. */
    // "noImplicitThis": true,                      /* Raise error on 'this' expressions with an implied 'any' type. */
    // "alwaysStrict": true,                        /* Parse in strict mode and emit "use strict" for each source file. */

    /* Additional Checks */
    // "noUnusedLocals": true,                      /* Report errors on unused locals. */
    // "noUnusedParameters": true,                  /* Report errors on unused parameters. */
    // "noImplicitReturns": true,                   /* Report error when not all code paths in function return a value. */
    // "noFallthroughCasesInSwitch": true,          /* Report errors for fallthrough cases in switch statement. */
    // "noUncheckedIndexedAccess": true,            /* Include 'undefined' in index signature results */
    // "noImplicitOverride": true,                  /* Ensure overriding members in derived classes are marked with an 'override' modifier. */
    // "noPropertyAccessFromIndexSignature": true,  /* Require undeclared properties from index signatures to use element accesses. */

    /* Module Resolution Options */
    "moduleResolution": "node",                  /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
    // "baseUrl": "./",                             /* Base directory to resolve non-absolute module names. */
    // "paths": {},                                 /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
    // "rootDirs": [],                              /* List of root folders whose combined content represents the structure of the project at runtime. */
    // "typeRoots": [],                             /* List of folders to include type definitions from. */
    // "types": [],                                 /* Type declaration files to be included in compilation. */
    // "allowSyntheticDefaultImports": true,        /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
    "esModuleInterop": true,                        /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    // "preserveSymlinks": true,                    /* Do not resolve the real path of symlinks. */
    // "allowUmdGlobalAccess": true,                /* Allow accessing UMD globals from modules. */

    /* Source Map Options */
    // "sourceRoot": "",                            /* Specify the location where debugger should locate TypeScript files instead of source locations. */
    // "mapRoot": "",                               /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,                     /* Emit a single file with source maps instead of having a separate file. */
    // "inlineSources": true,                       /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

    /* Experimental Options */
    // "experimentalDecorators": true,              /* Enables experimental support for ES7 decorators. */
    // "emitDecoratorMetadata": true,               /* Enables experimental support for emitting type metadata for decorators. */

    /* Advanced Options */
    "skipLibCheck": true,                           /* Skip type checking of declaration files. */
    "forceConsistentCasingInFileNames": true        /* Disallow inconsistently-cased references to the same file. */
  }
}

https://github.com/electron/electron/issues/21457

您還不能在 Electron 應用程序中使用 ES6 模塊。 VS Code 是一個 Electron 應用程序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM