Javascript 结合typescript和webpack读取节点js中的非js文件
我有一个用TypeScript编写的后端NodeJS设置,并使用webpack进行编译 当我试图读取一个文本文件时,当我确保source/test.txt被复制到build文件夹时,出现了这个错误 错误:Javascript 结合typescript和webpack读取节点js中的非js文件,javascript,node.js,typescript,webpack,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 directo
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') }
])
]
};
\uuuu dirname
被webpack设置为/
。目前,它试图找到/source/test.txt
,正如错误消息所说,它是文件系统的根。通过将node.dirname
设置为false
,您可以告诉webpack不要插入\uuuu dirname
,这样它将正确使用node.js\uu dirname
:
node: {
__dirname: false
}