如果直接写es6后运行node index.js
报错:SyntaxError: Cannot use import statement outside a module js
我们这里使用swc来将es6编译成CommonJS。
以后可以作为一个简单的框架模版使用。
- 安装
pnpm add @swc/cli @swc/core
- 配置.swcrc
{
"$schema": "https://swc.rs/schema.json",
"jsc": {
"parser": {
"syntax": "ecmascript",
"jsx": false,
"decorators": true
},
"transform": {
"legacyDecorator": true
},
"target": "es2021",
"loose": false
},
"module": {
"type": "commonjs",
"ignoreDynamic": true
},
"isModule": true,
"minify": false,
"sourceMaps": true
}
package.json
{
"name": "workers",
"version": "0.0.1",
"description": "",
"main": "cjs/index.js",
"module": "src/index.js",
"react-native": "src/index.js",
"private": true,
"exports": {
".": {
"import": "./src/index.js",
"require": "./cjs/index.js"
},
"./*": {
"import": "./src/*.js",
"require": "./cjs/*.js"
},
"./**/*": {
"import": "./src/**/*.js",
"require": "./cjs/**/*.js"
}
},
"keywords": [],
"author": "",
"license": "ISC",
"scripts": {
"prettier": "prettier --write .",
"clean": "shx rm -rf cjs coverage .nyc_output",
"build": "pnpm clean && swc ./workers -d ./cjs --strip-leading-paths",
"dev": "nodemon",
"start": "pnpm build && node --enable-source-maps ./cjs/index.js"
},
"nyc": {
"exclude": [
".*",
"cjs",
"test",
"**/*.spec.js"
]
},
"devDependencies": {
"@swc/cli": "^0.4.0",
"@swc/core": "^1.7.26",
"shx": "^0.3.4"
},
"prettier": {
"quoteProps": "consistent",
"printWidth": 120,
"singleQuote": true,
"trailingComma": "es5",
"tabWidth": 4,
"useTabs": false
}
}
nodemon.json
{
"watch": ["./src", "./conf"],
"ignore": ["./node_modules", "./deps/*"],
"ext": "js yaml",
"exec": "pnpm build && node --enable-source-maps ./cjs/index.js"
}
swc的其他配置:
添加重新编译配置
npm i -D chokidar
...
"build": "pnpm clean && swc ./workers -d ./cjs -d --strip-leading-paths",
...