使用typescipt和webpack

时间:2017-04-01 11:33:45

标签: javascript node.js typescript webpack

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

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

错误:

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

server.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') }
      ])
    ]
};

1 个答案:

答案 0 :(得分:1)

webpack将

if __name__ == '__main__': try: main() except ValueError: img2 = cv2.resize(img2,(320,320)) swap = cv2.resize(swap,(320,320)) dst = cv2.addWeighted(img2,0.55,swap,0.45,0) cv2.imwrite(sys.argv[3], dst) print "Shutting down" print "Exit" 设置为__dirname。目前,它会尝试查找/作为错误消息,这是您文件系统的根目录。您可以通过将/source/test.txt设置为__dirname来告诉webpack不要注入node.dirname,因此它会正确使用Node.js false

__dirname