Решил попробовать es6 модули Node.js (те, что .mjs или "type"="module"). Код пишу на typescript, компилировать код в js файлы должен ts-loader webpack`а. Проблема в том, что webpack не хочет дружить с es6 окружением и выдает ошибку:
Must use import to load ES Module webpack.config.js
// webpack.config.js
import path from 'path'
export default {
mode: 'development',
target: 'node',
entry: ['./main.ts'],
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/,
},
],
},
};
// package.json
{
"name": "31_mycms2",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"@types/express": "^4.17.7",
"@types/glob": "^7.1.3",
"@types/node": "^14.6.0",
"express": "^4.17.1",
"glob": "^7.1.6",
"module-alias": "^2.2.2",
"reflect-metadata": "^0.1.13",
"sqlite3": "^5.0.0",
"ts-loader": "^8.0.2",
"typeorm": "^0.2.25",
"typescript": "^4.0.2"
}
}
// tsconfig.json
{
"compilerOptions": {
"target": "ES2017",
"module": "ESNext",
"lib": ["ES2015"],
"strict": true,
"strictPropertyInitialization": false,
"moduleResolution": "node",
"baseUrl": ".",
"paths": {
"@root/*": ["./*"]
},
"esModuleInterop": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
}
}
// main.ts
import express from 'express'
const app = express();
app.listen(3000);
UPD:
Вот полный текст ошибки
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /home/admin/web/31_MyCMS2/webpack.config.js require() of ES modules is not supported.
require() of /home/admin/web/31_MyCMS2/webpack.config.js from /usr/lib/node_modules/webpack-cli/bin/utils/convert-argv.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename webpack.config.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /home/admin/web/31_MyCMS2/package.json.
переименовал webpack.config.js => webpack.config.mjs
добавил файл webpack.config.cjs:
module.exports = async (env, argv) => {
const config = await import('./webpack.config.mjs')
return config.default(env, argv)
}
вызываю webpack --config webpack.config.cjs --node-arg="--experimental-modules --experimental-vm-modules"
ошибка:
TypeError: Invalid host defined options at module.exports (/home/admin/web/31_MyCMS2/webpack.config.cjs:2:18)