Skip to content

webpack js模块搜索顺序 #60

@zhan2016

Description

@zhan2016

1.node中模块执行的顺序是先加载node自带的核心模块,再加载用户模块(就是我们写的),最后是加载第三方模块;
2.用户模块的查找规则:require("./index"),不写后缀名,查找规则为:index---index.js---index.json---index.node,require是node自带的文件导入方法,而import是ES6的导入方法;
3.第三方查找规则分为四种情况:

1.node_modules===>和文件一致的文件夹===>查找package.json===>查看是否有main属性,指向路径是否存在
2.无main:如果package.json中无main属性,或main的路径不存在,或物package.json文件,node加载index相关的文件(index.js,index.json,index.node)

3.无node_modules:如果node_modules找不到对应的模块文件夹,或无该文件夹,则向上一层文件夹查找index

4.如果上一级没找到继续上一级,查找到盘符未找到报错;cannot find modules XXX,如果没有npm init -y则会出现node_modules路径在c/用户/用户名

直接使用import ‘bootstrap-treeview’始终好不到文件,可是bootstrap-treeview明明已经在node_modules中了。这说明import的时候,虽然是用文件名来检索的,node_modules里面也有bootstrap-treeview这个文件夹,可是dist里面并没有自动补全的bootstrap-treeview.js, 只有bootstrap-treeview.min.js. 所以我们使用相对路径,让require到node_modules里面去找:

import "bootstrap-treeview/dist/bootstrap-treeview.min.js";
import   'bootstrap-treeview/dist/bootstrap-treeview.min.css';

同时,在import的时候,发现bootstrap-treeview.min.css解析有问题,需要在webpack.config.js里面添加loader:

[
            {
                test: /\.(scss)$/,
                use: [
                    {
                        // Adds CSS to the DOM by injecting a `<style>` tag
                        loader: 'style-loader'
                    },
                    {
                        // Interprets `@import` and `url()` like `import/require()` and will resolve them
                        loader: 'css-loader'
                    },
                    {
                        // Loader for webpack to process CSS with PostCSS
                        loader: 'postcss-loader',
                        options: {
                            plugins: function () {
                                return [
                                    require('autoprefixer')
                                ];
                            }
                        }
                    },
                    {
                        // Loads a SASS/SCSS file and compiles it to CSS
                        loader: 'sass-loader'
                    }
                ]  },{
                test: /\.css$/,     //添加这些!!!!!
                loader: "style-loader!css-loader"
             }
        ]

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions