在webpack 2中实现Tree shake会导致错误

时间:2017-02-13 05:56:31

标签: reactjs webpack babel webpack-2 native-module

我最近重构了我的应用程序以使用webpack v2。运行webpack -p之后,我注意到我的构建大小实际上增加了~32kb。我认为它没有实施树摇动。因此,在我的.babelrc文件中,我更改了此代码:

  "presets": [
    "react",
    "es2015",
    "stage-0",
  ]

==>

  "presets": [
    ["es2015", { "modules": false }],
    "react",
     "stage-0",
  ]

但现在我收到以下错误:

> webpack -p

C:\Users\jasan\Downloads\app\webpack.config.babel.js:1
(function (exports, require, module, __filename, __dirname) { import webpack fro
m 'webpack';
                                                              ^^^^^^
SyntaxError: Unexpected token import
    at Object.exports.runInThisContext (vm.js:76:16)
    at Module._compile (module.js:542:28)
    at loader (C:\Users\jasan\Downloads\app\node_modules\babel-register\lib\n
ode.js:144:5)
    at Object.require.extensions.(anonymous function) [as .js] (C:\Users\jasan\D
ownloads\app\node_modules\babel-register\lib\node.js:154:7)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at requireConfig (C:\Users\jasan\Downloads\app\node_modules\webpack\bin\c
onvert-argv.js:96:18)

2 个答案:

答案 0 :(得分:1)

问题在于,当webpack看到use Illuminate\Http\Request; public function deletepost(Request $request) // add Request to get the post data { $tagId = $request->input('id'); // here you define $tagId by the post data you send $post = post::find($tagId); if ($post) { $post->delete(); echo ('record is deleted!'); } else { echo 'record not found!'); } } 时,它会尝试将webpack.config.babel.js与预设的es2015和.babelrc一起使用,这意味着它会保留"modules": false个语句。但是node.js无法理解这种语法,因此您必须为节点提供CommonJS模块。

可能的解决方案之一是使用import/export param将配置从.babelrc直接移至webpack-loader

query

并在module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: "babel-loader", query: { "presets": [ "react", ["es2015", { "modules": false }], "stage-0" ] } } ] } 中只保留用于将导入转换为CommonJS的插件:

.babelrc

不要忘记向{ "plugins": ["transform-es2015-modules-commonjs"] }

添加必要的插件
package.json

有关详细信息,请同时查看此问题https://github.com/webpack/webpack/issues/1403

答案 1 :(得分:0)

webpack.config.js中的

使用Service

而不是

default