如何在 Webpack 4 中使用 ES6 import/export?

How to use ES6 import/export with Webpack 4?

我正在尝试让基本的 ES6 import/export 与 Webpack 4 一起工作,而 Webpack 似乎无法解析我的模块,尽管根据它正在查看的错误消息它:

$ make
./node_modules/.bin/webpack --mode production src/app.js -o dist/bundle.js
Hash: 6decf05b399fcbd42b01
Version: webpack 4.1.1
Time: 339ms
Built at: 2018-3-11 14:50:58
 1 asset
 Entrypoint main = bundle.js
    [0] ./src/app.js 41 bytes {0} [built]

ERROR in ./src/app.js
Module not found: Error: Can't resolve 'hello.js' in '/home/(myhomedir)/code/js/src'
 @ ./src/app.js 1:0-31 2:0-5                                    

这是我的设置(node_modulesdist 等省略):

$ npm ls --depth=0
.
├── webpack@4.1.1
└── webpack-cli@2.0.11

$ tree
.
├── Makefile
└── src
    ├── app.js
    └── hello.js

生成文件:

webpack = ./node_modules/.bin/webpack --mode production
entry = src/app.js

webpack: $(entry)
    $(webpack) $(entry) -o dist/bundle.js

src/app.js:

import {hello} from "hello.js";
hello();

src/hello.js:

function hello() {
    alert("yes it's hello");
}
export { hello };

我在 app.js 中的导入路径上尝试了很多变体,但它们都得到了相同的结果:Can't resolve 模块文件。我错过了什么?

您需要使用 babel 转译它并使用 babel-loader

此外,您不需要使用 make 只需使用 npm scripts.

存在错误,例如导入 import { hello } from 'hello.js' 而应该是 import { hello } from './hello.js' 或没有 .js,例如 import { hello } from './hello'

尝试以下 -

npm install --save-dev babel-core babel-loader babel-preset-env webpack@next webpack-cli

src/app.js

import { hello } from "./hello";
hello();

src/hello.js

function hello() {
  console.log("yes it's hello");
}
export { hello };

webpack.config.js

const path = require("path");

module.exports = {
  entry: "./src/app.js",

  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "bundle.js"
  },

  module: {
    rules: [
      {
        test: /\.js$/,
        loader: "babel-loader",
        exclude: /(node_modules)/
      }
    ]
  }
};

package.json

{
  "name": "webpack-test",
  "version": "1.0.0",
  "description": "",
  "main": "webpack.config.js",
  "scripts": {
    "build": "webpack --mode development",
    "prod": "webpack --mode production",
    "start": "node dist/bundle.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.4",
    "babel-preset-env": "^1.6.1",
    "webpack": "^4.0.0-beta.3",
    "webpack-cli": "^2.0.11"
  }
}

.babelrc

{
  "presets": ["env"]
}

首先 运行 npm run buildnpm run prod 然后 运行 npm run start 将记录输出

现代解决方案是使用 node.js 13+,然后将 "type": "module" 添加到 package.json 文件中。这将允许您使用导入语法而不是 require。更多信息在这里 https://nodejs.org/dist/latest-v13.x/docs/api/esm.html

Webpack 仍然需要 require 语法,所以你必须将 webpack.config.js 重命名为 webpack.config.cjs 然后通过将 webpack --config webpack.config.cjs 添加到你的 [=] 让 webpack 知道新的配置文件是什么23=] 脚本命令。如果 webpack 解决了 require

的问题,请关注这里 https://github.com/webpack/webpack-cli/issues/1165

这意味着您不需要任何 babel 或任何转译器。