webpack config无法使用ES6导入相对路径

时间:2018-03-20 21:21:03

标签: javascript webpack ecmascript-6 yarnpkg es6-modules

我已将我的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/.babelrcconfig/.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'正常工作?

1 个答案:

答案 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
    • 如果是CommonJS模块:返回module.exports
    • 如果是ES6模块:返回export default(这就是为什么它不适合你)
  • import * as all from module
    • 如果是CommonJS模块:返回module.exports
    • 如果是ES6模块:返回对象中的所有命名导出