如何在Webpack 4中使用ES6导入/导出?

use*_*783 6 webpack es6-modules webpack-4

我正在尝试获得基本的ES6 import/ exportWebpack 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                                    
Run Code Online (Sandbox Code Playgroud)

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

$ npm ls --depth=0
.
??? webpack@4.1.1
??? webpack-cli@2.0.11

$ tree
.
??? Makefile
??? src
    ??? app.js
    ??? hello.js
Run Code Online (Sandbox Code Playgroud)

生成文件:

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

webpack: $(entry)
    $(webpack) $(entry) -o dist/bundle.js
Run Code Online (Sandbox Code Playgroud)

src / app.js:

import {hello} from "hello.js";
hello();
Run Code Online (Sandbox Code Playgroud)

src / hello.js:

function hello() {
    alert("yes it's hello");
}
export { hello };
Run Code Online (Sandbox Code Playgroud)

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

dea*_*904 5

您需要使用babel进行编译并使用babel-loader

另外,您不需要仅使用npm scripts就可以使用make

还有像进口的错误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();
Run Code Online (Sandbox Code Playgroud)

src / hello.js

function hello() {
  console.log("yes it's hello");
}
export { hello };
Run Code Online (Sandbox Code Playgroud)

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)/
      }
    ]
  }
};
Run Code Online (Sandbox Code Playgroud)

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"
  }
}
Run Code Online (Sandbox Code Playgroud)

.babelrc

{
  "presets": ["env"]
}
Run Code Online (Sandbox Code Playgroud)

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


归档时间:

查看次数:

9304 次

最近记录:

7 年,10 月 前