【问题标题】:import not found: default error when using webpack for web development未找到导入:使用 webpack 进行 Web 开发时出现默认错误
【发布时间】:2021-04-04 19:17:26
【问题描述】:

我正在使用 webpack,一个 node.js 模块,以便捆绑 node.js 脚本以在浏览器中使用。该模块完成了它的意图,但是当我在浏览器中从 index.js 中得到一个奇怪的错误。问题似乎出在 index.js 上,但我不确定:

Uncaught SyntaxError: import not found: default.

我将在下面提供代码。

HTML:

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Typing Practice</title>
        <link rel="stylesheet" href="style.css">
        <script src="index.js" type="module" defer></script>
        <script src="wordpicker.js" type="module" defer></script>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <section id="top-container" class="top-bar">
            <h1 class="heading">Typing Practice</h1>
        </section>
        <section id="inpContainer" class="input-container">
            <div class="centeralign">
                <br><br>
                <h2 id="output" class="paragraph"></h2>
                <input type="text" id="input" class="text-field"><br>
                <button type="button" id="start" class="button">Start</button>
            </div>
        </section>
    </body>
</html>

JAVASCRIPT(我正在捆绑的脚本)

const rw = require('random-words');

function getWords() {
    let words = [];

    while (words.length != 10) {
        let word = rw();
        if (word.length < 6) continue;
        else if (word.length > 10) continue;
        else words.push(word)
    }
    return words;
}

export default getWords();

webpack.config.js 文件:

const path = require('path');

module.exports = {
  entry: './src/wordchecker.js',
  output: {
    filename: 'wordpicker.js',
    path: path.resolve(__dirname, 'dist'),
    library: 'typingpractice',
    libraryTarget: 'window',
    libraryExport: 'default'
  },
};

我在 index.js 中使用的导入语句: import getWords from './wordpicker.js';

如果您可以提供帮助或需要更多信息,请告诉我。

【问题讨论】:

    标签: javascript node.js webpack node-modules


    【解决方案1】:

    在 webpack.config.js 中,添加这个属性

      target: "node",
    

    这里也有错误:

     const rw = require('random-words');
     import rw from "random-words" 
    

    你不能再使用 require 了

    【讨论】:

    • 我应该用什么代替require?
    • @PacaAT import rw from "random-words"
    • 但是 random-words 是一个 node.js 模块,这不意味着你必须使用 require 吗?我在我的 index.js 文件中使用 import... from...
    猜你喜欢
    • 2021-08-10
    • 1970-01-01
    • 1970-01-01
    • 2018-02-10
    • 1970-01-01
    • 2019-09-08
    • 1970-01-01
    • 2022-08-16
    • 1970-01-01
    相关资源
    最近更新 更多