やりたいこと
- CommonJSの形式でexportされた(
module.exports
の形)複数のモジュールをjsファイルでimportし、一つのモジュールにまとめて再度exportする - 1で再度exportされたモジュールをtsファイルでimportする
※条件として1で記載したmodule.exports
の形式でexportされたモジュールをESのexportの書き方に変えることはできない
ご教示お願いします。
現在のコード
module.exportしているファイル(hoge.js)
前提としてこのファイルのexport方法は変更できないものとします。
js
1const hoge = { 2 key : 'value', 3} 4module.exports = hoge
複数のモジュールをimportして再度exportするファイル(sample.js)
js
1const hoge = require('./hoge'); 2const fuga = require('./fuga'); 3const sample = { 4 ...hoge,fuga 5}; 6module.exports = sample
importしたいファイル(import.ts)
ts
1import sample from './sample'; 2// hoge.jsとfuga.jsのJSONを出力したい 3console.log(sample);
現在のエラーメッセージ
アプリケーション起動時にブラウザのコンソールに以下のメッセージが出力されます。
怒られているのはhoge.jsです。
Uncaught TypeError: Cannot assign to read only property 'exports' of object '#<Object>'
試したこと
以下の記事を参考にしました。
①import.tsでのimport方法を変える
以下のように修正しましたが、エラーが発生します。
ts
1import sample from './sample'; 2↓ 3const sample = require('./sample');
エラーメッセージ(アプリケーション起動時)
import方法をrequiteに変更してもhoge.jsで同じメッセージで怒られます。
Uncaught TypeError: Cannot assign to read only property 'exports' of object '#<Object>'
②sample.jsのexport方法を変える
sample.jsのexport方法をmodule.exports
からexport default
とする。
js
1module.exports = sample 2↓ 3export default sample
エラーメッセージは変わらずでした。
hoge.jsで同じメッセージで怒られます。
Uncaught TypeError: Cannot assign to read only property 'exports' of object '#<Object>'
ビルド関連
babel.config.js
js
1module.exports = { 2 presets: [ 3 '@vue/app' 4 ] 5}
tsconfig.json
json
1{ 2 "compilerOptions": { 3 "target": "esnext", 4 "module": "esnext", 5 "strict": true, 6 "jsx": "preserve", 7 "importHelpers": true, 8 "moduleResolution": "node", 9 "experimentalDecorators": true, 10 "esModuleInterop": true, 11 "allowSyntheticDefaultImports": true, 12 "sourceMap": true, 13 "baseUrl": ".", 14 "types": [ 15 "webpack-env" 16 ], 17 "paths": { 18 "@/*": [ 19 "src/*" 20 ] 21 }, 22 "lib": [ 23 "esnext", 24 "dom", 25 "dom.iterable", 26 "scripthost" 27 ] 28 }, 29 "include": [ 30 "src/**/*.ts", 31 "src/**/*.tsx", 32 "src/**/*.vue", 33 "tests/**/*.ts", 34 "tests/**/*.tsx" 35 ], 36 "exclude": [ 37 "node_modules" 38 ] 39} 40
telint.json
json
1{ 2 "defaultSeverity": "warning", 3 "extends": [ 4 "tslint:recommended" 5 ], 6 "linterOptions": { 7 "exclude": [ 8 "node_modules/**" 9 ] 10 }, 11 "rules": { 12 "quotemark": [true, "single"], 13 "indent": [true, "spaces", 2], 14 "interface-name": false, 15 "ordered-imports": false, 16 "object-literal-sort-keys": false, 17 "no-consecutive-blank-lines": false, 18 "max-line-length": [true, {"limit": 120, "ignore-pattern": "^import | ^export {(.*?)}"}] 19 } 20} 21