[Nodejs, Typescript] Lỗi: Cannot use import statement outside a module
Mình vừa thêm 1 vài file .ts vào dự án nodejs, thì không npm start được (build tsc thì ok không lỗi gì)
Lỗi: Cannot use import statement outside a module
package.json node: 14.15.0
tsconfig.json
{
"compilerOptions": {
"target": "ES2016",
"module": "commonjs"
}
}
Bạn nào biết lỗi chỉ giúp mình với, thank you all.
5 ANSWERS
Update
Mình đã fix được lỗi, là do có 1 file .js có sử dụng cú pháp import ... from
(cái này chỉ dùng trong file .ts), mà đúng ra là phải dùng require()
.
Thank you all
Nodejs từ lâu đã sử dụng được import kiểu ES module rồi mà nhỉ. Bạn thử xem "type": "module"
đã có trong package.json chưa?
https://nodejs.org/api/esm.html#esm_modules_ecmascript_modules
@tranxuanthang nếu vậy thì cần đổi đuôi file .js
sang .mjs
anh à
Thêm cái này vào thì nó lại báo file bin/www không có đuôi file (trước giờ ko có đuôi file .js vẫn chạy ok đấy). T sửa thành www.js thì lại báo lỗi khác liên quan đến import. sao ra nhiều lỗi vậy nhỉ, từ khi thêm mấy file .ts này vào
const path = require('path');
const isProduction = false;
const mode = isProduction ? 'production' : 'development';
const devtool = isProduction ? false : 'inline-source-map';
module.exports = {
entry: './server/server.ts',
target: 'node',
mode,
devtool,
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
}
]
},
{
test: /\.ts$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
},
{
loader: 'ts-loader',
},
]
}
]
},
resolve: {
extensions: ['.js', '.ts', '.json' ]
},
output: {
filename: 'server.js',
path: path.resolve(__dirname, 'build'),
library: 'server', // very important line
libraryTarget: 'umd', // very important line
umdNamedDefine: true // very important line
},
node: {
__dirname: false,
__filename: false,
},
};
check chatwork đi a, e nhờ
{
"include": [
"src/**/*.ts"
],
"lib": [
"esnext",
"dom"
]
}
Bạn thử thêm cái này vào tsconfig.json
Bác cho ae xin cái script của alias "start" trong file
package.json
với được hơm?"scripts": { "start": "node bin/www" }
cái này à b