簡體   English   中英

如何在 Visual Studio 代碼中導入擴展名和文件?

[英]How to import extension along with files in visual studio code?

使用 nodejs 開發運行(--experimental-modules)

當前visual studio代碼智能導入如下

從“./config”導入配置;

但要求如下

從“./config.js”導入配置;

沒有 .js 得到如下錯誤

internal/modules/esm/resolve.js:61
  let url = moduleWrapResolve(specifier, parentURL);
            ^

Error: Cannot find module C:\Uday\Projects\practice-server\config imported from C:\Uday\Projects\practice-server\index.js
    at Loader.defaultResolve [as _resolve] (internal/modules/esm/resolve.js:61:13)
    at Loader.resolve (internal/modules/esm/loader.js:85:40)
    at Loader.getModuleJob (internal/modules/esm/loader.js:191:28)
    at ModuleWrap.<anonymous> (internal/modules/esm/module_job.js:42:40)
    at link (internal/modules/esm/module_job.js:41:36) {
  code: 'ERR_MODULE_NOT_FOUND'
}

所以我需要 Visual Studio 代碼智能來導入擴展??

//index.js
import express from "express";
import config from "./config.js";



const api_app = express();
const api_port = config.api_port
api_app.listen(api_port, () => {
    console.log(`Practice Server started on ${api_port}`);
});

//package.json
{
  "name": "practice-server",
  "type": "module",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1"
  }
}

//config.js
let config = function () { };

config.api_port = 6000;


export default config;

在全局設置(或項目設置)中,添加如下配置:

  // Preferred path ending for auto imports.
  //  - auto: Use project settings to select a default.
  //  - minimal: Shorten `./component/index.js` to `./component`.
  //  - index: Shorten `./component/index.js` to `./component/index`
  //  - js: Do not shorten path endings; include the `.js` extension.

  "javascript.preferences.importModuleSpecifierEnding": "js",

請注意,目前這僅適用於自動導入(即在引用另一個文件的導出時通過智能感知並且 VSCode 自動導入它)。 手動輸入導入語句時,它不適用於 autosuggest。

我總是像這樣使用我的 config.js。 也許它可以幫助你。

const config = require('./config');

//現在從配置訪問值

const sys_dbconfig = config_data['sys_database'];
const user = configdata['system_admin_name'];

這是我的 config.js

var config = {
"sys_database": {
    "user": 'postgres',
    "host": 'localhost',
    "database": 'postgres',
    "password": 'postgres',
    "port": "5432"
},
"system_admin_name": "system",
"url":"http://xxx.xx.x.xxx:3000/wscalc1?wsdl"
}

module.exports = config;

暫無
暫無

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

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