从外部模块导入

时间:2020-02-12 20:20:07

标签: javascript node.js typescript webpack

如何使用配置为...的Webpack来构建Webpack?

1。用TypeScript编写

2。是从Node模块导入的?

根据webpack docs,我可以用TypeScript编写Webpack配置。遵循这些文档,我可以使Webpack使用TS配置文件来构建Web,其源代码在同一项目中

如果我使用相同的源代码并将其移至node_modules/my-webpack-config/config.ts,然后将webpack指向该源代码,则它不起作用-webpack无法识别配置文件中的TS,并且出现如下错误:

/Users/tuff/_dev/myproject/node_modules/my-webpack-config/config.ts:1
import { Configuration } from 'webpack';
       ^

SyntaxError: Unexpected token {
    at Module._compile (internal/modules/cjs/loader.js:872:18)
    at Module._extensions..js (internal/modules/cjs/loader.js:947:10)
    at Object.require.extensions.<computed> [as .ts] (/Users/tuff/_dev/myproject/node_modules/ts-node/src/index.ts:807:44)
    at Module.load (internal/modules/cjs/loader.js:790:32)
    at Function.Module._load (internal/modules/cjs/loader.js:703:12)
    at Module.require (internal/modules/cjs/loader.js:830:19)
    at require (internal/modules/cjs/helpers.js:68:18)
    at Object.<anonymous> (/Users/tuff/_dev/myproject/config/webpack.dev.ts:2:16)
    at Module._compile (internal/modules/cjs/loader.js:936:30)
    at Module.m._compile (/Users/tuff/_dev/myproject/node_modules/ts-node/src/index.ts:814:23)

我尝试直接使用

将配置文件提供给Webpack
webpack --config ./node_modules/my-webpack-config/config.ts

或间接通过本地文件从node_modules重新导出配置:

import config from 'my-webpack-config/config';

export default config;

两种方法都给出相同的错误。

TS编译器是否忽略了node_modules中的配置?也许...所以我尝试将路径添加到tsconfig的files列表中,以确保将其包含在TS编译中:

  "files": [
    "./node_modules/my-webpack-config/config.ts"
  ]

...什么都没改变-同样的错误。这是我的完整tsconfig.json,位于项目根目录:

{
  "include": ["../src"],
  "exclude": ["../dist"],
  "files": [
    "./node_modules/my-webpack-config/config.ts"
  ],
  "compilerOptions": {
    "forceConsistentCasingInFileNames": true,
    "jsx": "react",
    "lib": ["dom", "es2017", "esnext.asynciterable"],
    "module": "commonjs",
    "moduleResolution": "node",
    "noEmitOnError": true,
    "noFallthroughCasesInSwitch": true,
    "noImplicitReturns": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "outDir": "../dist",
    "resolveJsonModule": true,
    "sourceMap": true,
    "strict": true,
    "target": "es2017",
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true
  }
}

请注意,我还尝试定义exclude列表以覆盖this default behaviour of tsconfig

默认情况下,“ exclude”属性会排除node_modulesbower_componentsjspm_packages和`目录。

那...怎么了?

0 个答案:

没有答案