我已将我的Webpack配置文件从CommonJS转换为ES6模块到cjs-to-es6。一些ES6导入语句如下:
import config from '../config'
虽然这条线不起作用
import utils from './utils'
导致此错误
$ babel-node ./node_modules/.bin/webpack-dev-server --inline --progress --config build/webpack.dev.conf.js
/my/directory/build/vue-loader.conf.js:34
loaders: _utils2.default.cssLoaders({
^
TypeError: Cannot read property 'cssLoaders' of undefined
at Object.<anonymous> (/my/directory/build/vue-loader.conf.js:19:18)
at Module._compile (module.js:649:30)
at loader (/Users/hanxue/.config/yarn/global/node_modules/babel-register/lib/node.js:144:5)
at Object.require.extensions.(anonymous function) [as .js] (/Users/hanxue/.config/yarn/global/node_modules/babel-register/lib/node.js:154:7)
at Module.load (module.js:561:32)
at tryModuleLoad (module.js:501:12)
at Function.Module._load (module.js:493:3)
at Module.require (module.js:593:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (/my/directory/build/webpack.base.conf.js:5:1)
error An unexpected error occurred: "Command failed.
更改
import utils from './utils'
到
const utils = require('./utils')
将消除错误消息。
webpack:4.0.1 node:v9.8.0 纱线:1.5.1
$ ls -a config/
. .babelrc index.js test.env.js
.. dev.env.js prod.env.js
$ ls -a build/
. check-versions.js webpack.base.conf.js
.. logo.png webpack.dev.conf.js
.babelrc utils.js webpack.prod.conf.js
build.js vue-loader.conf.js webpack.temp.js
build/.babelrc
和config/.babelrc
的内容:
{
"presets": ["es2015"]
}
相关的package.json
内容
"scripts": {
"dev": "babel-node ./node_modules/.bin/webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
"start": "npm run dev",
"unit": "jest --config test/unit/jest.conf.js --coverage",
"e2e": "node test/e2e/runner.js",
"test": "npm run unit && npm run e2e",
"lint": "eslint --ext .js,.vue src test/unit/specs test/e2e/specs",
"build": "node build/build.js"
},
如何让import utils from './utils'
正常工作?
答案 0 :(得分:0)
将import utils from './utils'
替换为import * as utils from './utils'
。
import something from 'module'
将default
export
导入something
import * as something from 'module'
将所有内容导入something
仅当utils.js
是ES6模块(我假设)时才有效,如果它是CommonJS模块(module.exports
)则两者都应该有效。
在运行时,Babel CommonJS插件将检查模块是ES6还是CommonJS(使用__esModule
)和:
import default from module
:
module.exports
export default
(这就是为什么它不适合你)import * as all from module
:
module.exports