首页 > require 为何时灵时不灵

require 为何时灵时不灵

__resourceQuery 是 Webpack 中的常量。

这样是可以的:

const hotClient = require('webpack-hot-middleware/client' + __resourceQuery)

而这样是不行的:

const hotClient = require(`webpack-hot-middleware/client${__resourceQuery}`)

为啥用了 ES6 的字符串模板之后就不灵了呢=。=


补充:

es6 肯定是开了的,Babel 也是装了的。

我疑问的是,理论上 require import 应该都不允许变量构建才对,为什么 require 可以 warning 而 import 直接 error 了。

怪我表述不清,所有的情况如下:

  1. 使用 import + 变量:

  const r = './LeftBar.vue'
  import LeftBar from r

babel 报错:

Module build failed: SyntaxError: /Main.vue: Unexpected token (16:20)
  1. 使用 import + template :

  const r = './LeftBar.vue'
  import LeftBar from `${r}`

babel 报错:

Module build failed: SyntaxError: /Main.vue: Unexpected token (16:20)
  1. 使用 require + template:

  const r = './LeftBar.vue'
  const LeftBar = require(`${r}`)

没有问题

  1. 使用 require + 变量:

  const r = './LeftBar.vue'
  const LeftBar = require(r)

warning:

            18:14-24 the request of a dependency is an expression

不过后来想想是我傻逼了。。。require 直接引入 var 是不走 babel 的,而其他 babel 其实都编译过了=。=表现不同也正常


既然用了es6,为什么不用import


你的第二种是es6写法,好些浏览器是不支持的,需要用bable解析成es5的,建议你查下webpack>bable>es6,当然bable只是其中一种解析方式~


不灵的意思是,报错了?还是编译出来的内容不正确?


楼上说的正解,es6 template-literals 需要转换才能用

http://babeljs.io/docs/plugins/transform-es2015-template-literals/

【热门文章】
【热门文章】