javascript - 结合typescript和webpack读取node js中的非js文件

标签 javascript node.js typescript webpack

我有一个用 TypeScript 编写的后端 NodeJS 设置,并使用 webpack 来编译它。

当我尝试读取文本文件时,当我确保将 source/test.txt 复制到构建文件夹时,我收到此错误。

错误:

fs.js:640
  return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode);
                 ^

Error: ENOENT: no such file or directory, open '/source/test.txt'
    at Error (native)
    at Object.fs.openSync (fs.js:640:18)
    at Object.fs.readFileSync (fs.js:508:33)

我的项目结构

project
-- build
-- server
---- server.tsx
---- source
------ test.txt

服务器.tsx

import * as express from 'express'
import * as Path from 'path'
import * as fs from 'fs'

const app = express()

const textFile = fs.readFileSync(Path.join(__dirname, "./source/test.txt"))

app.listen(3000, () => console.log(`running on port 3000`))

$ webpack && node build/server.js

tsconfig.json

{
    "compilerOptions": {
        "outDir": "./build",
        "sourceMap": false,
        "noImplicitAny": false,
        "module": "commonjs",
        "target": "es5",
        "strictNullChecks": true
    },
    "include": [
        "./server/**/*"
    ],
    "exclude": [
        "node_modules"
    ]
}

webpack.config.js

const CopyWebpackPlugin = require('copy-webpack-plugin')
const Path = require('path')

module.exports = {
    entry: "./server/server.tsx",
    target: 'node',
    output: {
        filename: "server.js",
        path: __dirname + "/build"
    },

    resolve: {
        extensions: [".ts", ".tsx", ".js", ".json"]
    },

    module: {
        rules: [
            // All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'.
            { test: /\.tsx?$/, loader: "awesome-typescript-loader" },

            // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
            { enforce: "pre", test: /\.js$/, loader: "source-map-loader" }
        ]
    },

    plugins: [
      new CopyWebpackPlugin([
        { from: Path.join(__dirname, './server/source'), to: Path.join(__dirname, './build/source') }
      ])
    ]
};

最佳答案

__dirname 被 webpack 设置为 /。目前,它尝试按照错误消息所述查找 /source/test.txt,这是文件系统的根目录。您可以通过将 node.dirname 设置为 false 来告诉 webpack 不要注入(inject) __dirname,这样它将正确使用 Node.js __dirname:

node: {
  __dirname: false
}

关于javascript - 结合typescript和webpack读取node js中的非js文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43156294/

相关文章:

javascript - 传递 json 并获取结果取决于 2 行 - javascript

javascript - 在 javascript 类中调用类方法

javascript - Node : How return different content types with same response (text and image)?

json - JSON 模式中的一组属性中的一个或一个都没有

c# - 在 C# 中运行 Javascript 的最可靠方法?

javascript - Electron 渲染器过程: When Should I Clean IPC Listeners

javascript - 处理 'Internet not Available' 的最佳实践(Angular、Ionic、Cordova 应用程序)

node.js - NPM 安装错误

javascript - Node js Express静态未收到客户端的post响应

typescript - Angular 2 - 如何从组件访问指令